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 | class ComicboxOnlineLookup(ComicboxOnlineCovers):
"""Pulls online metadata into the source pool before merge runs."""
# Class-level so tests can override (and per-instance attrs override that).
_ONLINE_SOURCE_FACTORIES: ClassVar[MappingProxyType[str, Any]] = (
_DEFAULT_SOURCE_FACTORIES
)
# Process-wide lock around the selector callback. Under `-j N` parallel
# batch runs we serialise prompts so output stays readable and the user
# can see which file is being asked about. It guards only the callback
# itself; the mutable lookup policy has its own lock (OnlineSessionState).
_PROMPT_LOCK: ClassVar[threading.Lock] = threading.Lock()
# Per-instance selector override; falls back to the default CLI prompt.
_online_selector: SelectorCallback | None = None
# Session-supplied owner of the two mutable lookup settings (match and
# prompts). A Runner or OnlineSession shares one across every box it
# spawns so a `set_policy` / `set_prompts` answered on one file is
# in force for the next. Unset for a standalone Comicbox: the lazy
# fallback below then makes a private one seeded from this box's
# config, keeping single-file use self-contained.
_online_session_state: OnlineSessionState | None = None
# Per-instance event handler; emits SearchStarted / AutoWritten / etc.
# for callers driving online lookup programmatically (OnlineSession).
_event_handler: EventHandler | None = None
# Per-instance series cache (series-first batching, plan §3.10). When
# set, the matcher consults it before the cold-path search: a cache
# hit triggers source.lookup_issue(volume_id, number) instead. The
# cache key is (source_name, series_fingerprint); the value is the
# resolved volume_id. Populated on each cold-path acceptance using
# ``setdefault`` so the first writer wins — falsy-group collisions
# don't get to overwrite the original.
_series_cache: MutableMapping[tuple[str, str], int] | None = None
# How many comics of THIS comic's series the current batch holds.
# Set by the dispatcher (CLI `Runner`, `OnlineSession.tag_many`);
# 1 for a standalone file. The source that resolves the series uses
# it to decide whether listing the whole series once is cheaper than
# one lookup per comic (see `OnlineSource.prefetch_volume`).
_series_cluster_size: int = 1
# Session-supplied retry-sleep override propagated to every active
# online source (see set_retry_sleep).
_retry_sleep: Callable[[float], None] | None = None
_online_lookup_done_flag: bool = False
# Whether the completed lookup applied online metadata; repeat
# run_online_lookup() calls report this first-run outcome.
_online_lookup_won: bool = False
# Built once per lookup run (5 call sites); invalidated whenever the
# source caches reset because the profile reads non-online sources.
_profile_cache: ComicProfile | None = None
@override
def _reset_loaded_forward_caches(self) -> None:
super()._reset_loaded_forward_caches()
self._profile_cache = None
def set_online_selector(self, selector: SelectorCallback | None) -> None:
"""Register a programmatic selector callback (codex / library users)."""
self._online_selector = selector
def set_event_handler(self, handler: EventHandler | None) -> None:
"""Register an event-stream callback for online-lookup progress."""
self._event_handler = handler
def set_series_cache(
self, cache: MutableMapping[tuple[str, str], int] | None
) -> None:
"""Register a session-level series cache for series-first batching."""
self._series_cache = cache
def set_series_cluster_size(self, size: int) -> None:
"""Tell this box how many comics of its series the batch holds."""
self._series_cluster_size = max(1, size)
def set_online_session_state(self, state: OnlineSessionState | None) -> None:
"""
Register the session-level owner of match mode and prompt policy.
Share one across every box of a batch so a `set_policy` /
`set_prompts` answered at a prompt outlives the file it was
answered on. A sibling worker already resolving a file finishes it
under the policy it started with and picks the change up on its
next file.
"""
self._online_session_state = state
def _get_online_session_state(self) -> OnlineSessionState:
"""Get the session state, defaulting to a box-private one."""
if self._online_session_state is None:
self._online_session_state = OnlineSessionState.from_lookup(
self._config.online.lookup
)
return self._online_session_state
def _session_online(self) -> OnlineSettings:
"""Read the live lookup policy onto this box's online settings."""
return self._get_online_session_state().overlay(self._config.online)
def set_retry_sleep(self, sleep: Callable[[float], None] | None) -> None:
"""
Register a retry-sleep override for this box's online sources.
OnlineSession wires this to a cancel-event wait so a caller's
cancel() can interrupt multi-minute rate-limit sleeps instead of
blocking until the retry budget plays out. The callable may raise
(e.g. OnlineLookupAbortedError) to abort the in-flight lookup.
"""
self._retry_sleep = sleep
def _emit(self, event: Event) -> None:
"""No-op if no handler is registered, else forward the event."""
if self._event_handler is not None:
self._event_handler(event)
def _on_source_rate_limit(self, source_name: str, delay: float | None) -> None:
"""Emit a RateLimited event when a source hits a rate limit."""
self._emit(RateLimited(source=source_name, retry_after_seconds=delay))
def _online_lookup_already_done(self) -> bool:
return self._online_lookup_done_flag
def _mark_online_lookup_done(self) -> None:
self._online_lookup_done_flag = True
def _warn_unconfigured_source(self, name: str, online: OnlineSettings) -> None:
"""
Loud warning when a user-requested source can't run for credential reasons.
Quiet skip when the source was only included via the `all` sentinel
— in that case we don't know the user wanted this specific source.
"""
explicit_id = online.lookup.ids.get(name)
if explicit_id is not None:
logger.warning(
f"online: --id {name}:{explicit_id} requested but {name} is "
f"not configured (missing credentials); skipping"
)
return
explicit_sid = online.lookup.series_ids.get(name)
if explicit_sid is not None:
logger.warning(
f"online: --series-id {name}:{explicit_sid} requested but "
f"{name} is not configured (missing credentials); skipping"
)
return
# Was the source named explicitly via `--online <list>`? selected
# is None for the `all` sentinel; only warn for explicit lists.
if online.lookup.sources is not None and name in online.lookup.sources:
logger.warning(
f"online: --online {name} requested but {name} is not "
f"configured (missing credentials); skipping"
)
def _online_run_order(self, online: OnlineSettings) -> tuple[str, ...]:
"""
Name the online sources in run order, which is also merge precedence.
The selection's order when there is one, else every source in the
factory map's default order (``SOURCE_NAMES``). Under first-wins
the first source that contributes data ends the lookup; with every
source queried, the first one wins where their tags disagree.
"""
return tuple(online.lookup.sources or self._ONLINE_SOURCE_FACTORIES)
def _build_active_online_sources(
self, online: OnlineSettings
) -> list[OnlineSource]:
"""
Resolve which configured online sources participate in this run.
The selection's order is the run order: under first-wins, the
first source that contributes data ends the lookup, so an admin
listing ``[comicvine, metron]`` makes Comic Vine the primary and
Metron the fallback. An empty/None selection runs every
configured source in the factory map's default order.
"""
active: list[OnlineSource] = []
for name in self._online_run_order(online):
factory = self._ONLINE_SOURCE_FACTORIES.get(name)
if factory is None:
# Config-layer normalization warns and drops unknown names;
# this guards programmatic settings that bypass it.
logger.warning(f"online: unknown source {name!r}; skipping")
continue
creds = online.auth.sources.get(name)
if creds is None:
self._warn_unconfigured_source(name, online)
continue
source = factory(creds, online)
if not source.is_configured():
self._warn_unconfigured_source(name, online)
continue
source.on_rate_limit = self._on_source_rate_limit
source.retry_sleep = self._retry_sleep
active.append(source)
return active
def _stored_identifier(self, source_name: str) -> int | None:
"""
Return the upstream issue id for `source_name` stored on the comic, if any.
Scans every non-online normalized source for
``comicbox.identifiers.<source_name>.key`` and returns the first
value that parses as an int. Used to drive a fast `source.get(id)`
refresh in lieu of a full search when the comic was previously
tagged. Returns None when no parseable stored id is found.
"""
keypath = f"comicbox.identifiers.{source_name}.key"
for src in MetadataSources:
if src in _ONLINE_SOURCE_ENUMS:
continue
normalized = self.get_normalized_metadata(src)
if not normalized:
continue
for loaded in normalized:
raw = glom(dict(loaded.metadata), keypath, default=None)
if raw is None:
continue
try:
return int(raw)
except (TypeError, ValueError):
continue
return None
def _wrap_payload(self, source: OnlineSource, payload: dict[str, Any]) -> dict:
"""Wrap raw API response under the format's ROOT_TAG for schema.load."""
schema_class = source.metadata_format.value.schema_class
return {schema_class.ROOT_TAG: payload}
def _fetch_explicit_id(self, source: OnlineSource, issue_id: int) -> bool:
"""Fetch one issue by id and inject it as a source. True on success."""
try:
payload = source.get(issue_id)
except OnlineLookupAbortedError:
raise
except Exception as exc:
logger.warning(
f"online {source.name}: fetch by id={issue_id} failed: {exc}"
)
return False
wrapped = self._wrap_payload(source, payload)
self.add_source(
source.metadata_source,
wrapped,
fmt=source.metadata_format,
)
logger.debug(f"online {source.name}: added id={issue_id}")
return True
def _build_profile(self) -> ComicProfile:
"""
Read the non-online merged-so-far metadata into a ComicProfile.
Memoized per run: the lookup flow consults the profile several
times and only non-online sources feed it, so it can't change
mid-lookup (cache invalidation rides _reset_loaded_forward_caches).
"""
if self._profile_cache is not None:
return self._profile_cache
# Collect from non-online normalized sources, last-wins, so the
# profile's precedence matches the main merge (embedded archive
# files beat the filename parse). See accumulate_profile_fields.
fields: dict[str, Any] = {}
for src in MetadataSources:
if src in _ONLINE_SOURCE_ENUMS:
continue
normalized = self.get_normalized_metadata(src)
if not normalized:
continue
for loaded in normalized:
accumulate_profile_fields(fields, dict(loaded.metadata))
profile = ComicProfile(
series=fields.get("series"),
issue=fields.get("issue"),
issue_int=parse_issue_int(fields.get("issue")),
year=fields.get("year"),
publisher=fields.get("publisher"),
page_count=fields.get("page_count"),
volume=fields.get("volume"),
series_start_year=fields.get("series_start_year"),
)
self._profile_cache = profile
return profile
def _accept(
self,
source: OnlineSource,
issue_id: int,
record: Callable[[str], None],
*,
emit_auto_written: bool,
candidate: Candidate | None = None,
) -> bool:
"""
Turn an issue id into applied metadata; the one accept chokepoint.
Every accepting path funnels through here so "we counted a win"
and "metadata was added" cannot drift apart: the outcome counter,
the ``AutoWritten`` event and the series-cache population all run
*after* the fetch and only when it succeeded. Ordering used to be
per-caller, and three of them recorded the win first, so a failed
follow-up fetch still incremented the summary and emitted the
event. `_fetch_explicit_id` logs its own failure, so a False
return is silent here.
"""
if not self._fetch_explicit_id(source, issue_id):
return False
record(source.name)
if candidate is not None:
self._maybe_populate_series_cache(source, candidate)
if emit_auto_written:
self._emit_auto_written(source, issue_id)
return True
def _accept_candidate(self, source: OnlineSource, candidate: Candidate) -> bool:
"""Accept a ranked candidate as an auto-write. True when applied."""
return self._accept(
source,
candidate.issue_id,
outcome_stats.record_auto_write,
emit_auto_written=True,
candidate=candidate,
)
def _maybe_populate_series_cache(
self, source: OnlineSource, candidate: Candidate
) -> None:
"""
Cache the resolved series volume_id on cold-path acceptance.
First-writer-wins: a falsy-group collision (two unrelated comics
that happened to share a series fingerprint) can't overwrite an
already-resolved entry. Fires ``SeriesIdentified`` only on first
population for this fingerprint.
``claim_series`` makes "was I the first writer?" a single
operation, so concurrent callers (the CLI's `-j N` pool, which
shares one cache across workers) get exactly one winner and
therefore exactly one event. A plain dict from a single-threaded
caller still works — it degrades to the check-then-set this used
to do inline.
"""
if self._series_cache is None or candidate.volume_id is None:
return
fingerprint = _series_fingerprint(self._build_profile())
key = (source.name, fingerprint)
if not claim_series(self._series_cache, key, candidate.volume_id):
return
self._emit(
SeriesIdentified(
path=getattr(self, "_path", None),
source=source.name,
series_fingerprint=fingerprint,
volume_id=candidate.volume_id,
)
)
# This worker resolved the series, so it is the one that pays for
# the prefetch — and it does so while still holding the
# single-flight lead, so the rest of the cluster waits for a warm
# list rather than racing it with per-issue lookups.
source.prefetch_volume(candidate.volume_id, self._series_cluster_size)
def _resolve_with_matcher(
self, source_name: str, candidates: list[Candidate], online: OnlineSettings
) -> Resolution:
ranked = self._rank_candidates(
self._build_profile(), source_name, candidates, online
)
return OnlineMatcher().resolve(ranked, online, source_name)
def _selector_for_run(self) -> SelectorCallback:
return self._online_selector or cli_selector
def _handle_prompt(
self, source: OnlineSource, candidates: tuple[Candidate, ...]
) -> bool:
"""
Drive the selector callback for the PROMPT case.
Acquires the class-level `_PROMPT_LOCK` around the selector call
so concurrent worker threads (when `-j N > 1`) don't garble each
other's prompts. Re-resolves and re-prompts when the selector
requests a session-level setting change (`set_prompts` /
`set_policy`), reading the session state back so the new setting
takes effect on the current candidate set immediately.
Returns True when the prompt led to accepted metadata.
"""
current = candidates
path = getattr(self, "_path", None)
prompt_id = f"{source.name}:{id(candidates)}"
for _ in range(_MAX_PROMPT_ROUNDS):
self._emit(
PromptQueued(
path=path,
source=source.name,
prompt_id=prompt_id,
n_candidates=len(current),
)
)
result = self._invoke_selector(source, current)
action, payload = result
self._emit(
PromptResolved(
path=path,
source=source.name,
prompt_id=prompt_id,
action=action,
)
)
if action in {"set_prompts", "set_policy"}:
if not self._apply_session_action(source.name, action, payload):
return False
resolution = self._resolve_existing(
source.name, list(current), self._session_online()
)
terminal = self._apply_terminal_resolution(
source, resolution, path, context="after session change"
)
if terminal is not None:
return terminal
current = resolution.candidates
continue
return self._dispatch_terminal_prompt_action(
source, current, action, payload
)
# Only `set_prompts` / `set_policy` reach here; every other
# action returned above. A selector that keeps asking for session
# changes without ever deciding would have spun forever.
logger.warning(
f"online {source.name}: selector requested a session change "
f"{_MAX_PROMPT_ROUNDS} times without choosing; skipping"
)
outcome_stats.record_prompt_declined(source.name)
return False
def _invoke_selector(
self, source: OnlineSource, candidates: tuple[Candidate, ...]
) -> SelectorResult:
selector = self._selector_for_run()
ctx = SelectorContext(
file_path=getattr(self, "_path", None),
source=source.name,
# Overlaid so a selector reading the current match mode or
# prompt policy sees the live session values, not the ones
# config resolution started the run with.
settings=replace(self._config, online=self._session_online()),
triggered_hashing=any(c.cover_score is not None for c in candidates),
enrich_candidates=source.enrich_prompt_candidates,
)
with type(self)._PROMPT_LOCK: # noqa: SLF001 — class-level lock by design
return selector(self._build_profile(), candidates, ctx)
def _apply_session_action(
self, source_name: str, action: str, payload: int | str | None
) -> bool:
"""
Apply a `set_prompts` / `set_policy` action to the session.
The single validator for these two actions: the session reads the
state this writes, so there is no second implementation to keep in
step. Both name their new value as a string payload, so both parse
it the same way. Returns True on success, False if the payload was
malformed (in which case the prompt has been recorded as declined
and the caller should bail out).
"""
enum_class: type[Prompts | MatchMode] = (
Prompts if action == "set_prompts" else MatchMode
)
noun = "prompt policy" if action == "set_prompts" else "match mode"
if not isinstance(payload, str):
logger.warning(
f"online {source_name}: {action} requires a {noun} name; "
f"got {payload!r}"
)
outcome_stats.record_prompt_declined(source_name)
return False
try:
new_value = enum_class(payload)
except ValueError:
expected = " | ".join(member.value for member in enum_class)
logger.warning(
f"online {source_name}: unknown {noun} {payload!r}; "
f"expected one of {expected}"
)
outcome_stats.record_prompt_declined(source_name)
return False
state = self._get_online_session_state()
if isinstance(new_value, Prompts):
state.set_prompts(new_value)
else:
state.set_match(new_value)
logger.info(
f"online {source_name}: session {noun} set to {new_value.value} via prompt"
)
return True
def _resolve_existing(
self, source_name: str, ranked: list[Candidate], online: OnlineSettings
) -> Resolution:
"""Re-apply policy to an already-ranked candidate list."""
return OnlineMatcher().resolve(ranked, online, source_name)
def _apply_terminal_resolution(
self,
source: OnlineSource,
resolution: Resolution,
path: Path | None,
context: str = "",
) -> bool | None:
"""
Handle the terminal resolution kinds with logging, stats, and events.
The single implementation for both the cold path and the
re-resolution after a session change (``context`` only varies the
log suffix) so programmatic event consumers see AutoWritten /
Skipped / NoMatch on every path.
Returns None when the resolution is still PROMPT (caller decides
how to prompt); True when terminal and the candidate's metadata
was added; False when terminal without an accepted result.
"""
suffix = f" {context}" if context else ""
if resolution.kind is ResolutionKind.AUTO_WRITE and resolution.chosen:
logger.info(
f"online {source.name}: auto-writing "
f"id={resolution.chosen.issue_id} "
f"(score={resolution.chosen.score:.2f}){suffix}"
)
return self._accept_candidate(source, resolution.chosen)
if resolution.kind is ResolutionKind.NO_MATCH:
logger.info(
f"online {source.name}: no match cleared min_confidence{suffix}"
)
outcome_stats.record_no_match(source.name)
self._emit(NoMatch(path=path, source=source.name))
return False
if resolution.kind is ResolutionKind.SKIP:
top = resolution.candidates[0].score if resolution.candidates else 0
logger.info(
f"online {source.name}: skipped "
f"(matcher declined; top={top:.2f}){suffix}"
)
outcome_stats.record_skip(source.name)
self._emit(
Skipped(path=path, source=source.name, reason=SKIP_MATCHER_DECLINED)
)
return False
return None
def _dispatch_terminal_prompt_action(
self,
source: OnlineSource,
candidates: tuple[Candidate, ...],
action: str,
payload: int | str | None,
) -> bool:
"""Apply a terminal prompt action. True when metadata was accepted."""
if action == "choose" and isinstance(payload, int):
if not 0 <= payload < len(candidates):
# A selector index is untrusted input, same as in
# OnlineSession._store_prompt_resolution. Unguarded, a
# negative index is a legal Python from-the-end lookup, so
# the comic gets tagged with a candidate nobody chose.
logger.warning(
f"online {source.name}: prompt chose index {payload} but "
f"only {len(candidates)} candidate(s) were offered; skipping"
)
outcome_stats.record_prompt_declined(source.name)
return False
chosen = candidates[payload]
logger.info(f"online {source.name}: prompt-chose id={chosen.issue_id}")
return self._accept(
source,
chosen.issue_id,
outcome_stats.record_prompt_accepted,
emit_auto_written=False,
candidate=chosen,
)
if action == "manual" and isinstance(payload, str):
try:
src_name, _, raw_id = payload.partition(":")
issue_id = int(raw_id)
except ValueError:
logger.warning(f"online: manual id {payload!r} is not <source>:<int>")
outcome_stats.record_prompt_declined(source.name)
return False
if src_name.strip().lower() != source.name:
logger.warning(
f"online {source.name}: manual id {payload!r} routes to "
f"a different source; skipping"
)
outcome_stats.record_prompt_declined(source.name)
return False
return self._accept(
source,
issue_id,
outcome_stats.record_prompt_accepted,
emit_auto_written=False,
)
if action == "abort":
reason = "online: aborted by user from prompt"
raise OnlineLookupAbortedError(reason)
logger.info(f"online {source.name}: skipped via prompt")
outcome_stats.record_prompt_declined(source.name)
return False
def _run_search(
self, source: OnlineSource, profile: ComicProfile, path: Path | None
) -> tuple[list[Candidate] | None, str]:
"""
Invoke source.search and emit SearchCompleted.
`_search_path` has already emitted SearchStarted, once for the
cover search and this name search together.
"""
search_issue = strip_issue_leading_zeros(profile.issue)
criteria_summary = (
f"series={profile.series!r} issue={search_issue!r} year={profile.year}"
)
logger.info(f"online {source.name}: searching with {criteria_summary}")
try:
candidates = source.search(profile)
except OnlineLookupAbortedError:
# A cancelled retry sleep aborts the whole lookup, not just
# this search.
raise
except Exception as exc:
logger.warning(f"online {source.name}: search failed: {exc}")
return None, criteria_summary
top_score = candidates[0].score if candidates else None
self._emit(
SearchCompleted(
path=path,
source=source.name,
n_candidates=len(candidates),
top_score=top_score,
)
)
return candidates, criteria_summary
def _apply_resolution(
self,
source: OnlineSource,
resolution: Resolution,
path: Path | None,
) -> bool:
"""
Dispatch on resolution kind: auto-write, no-match, skip, or prompt.
Returns True when the resolution led to accepted metadata.
"""
terminal = self._apply_terminal_resolution(source, resolution, path)
if terminal is not None:
return terminal
# ResolutionKind.PROMPT — invoke the selector callback.
return self._handle_prompt(source, resolution.candidates)
def _search_path(self, source: OnlineSource, online: OnlineSettings) -> bool:
"""
Search → rank → resolve → fetch on accept. True when accepted.
A source that can search by cover is asked that first. A cover
match its verdict accepts is written without the name search,
except under ``ask``. Cover rows that weren't written are offered
if the name search ends in a prompt or finds nothing.
"""
profile = self._build_profile()
path = getattr(self, "_path", None)
if not _has_search_criteria(source.name, profile):
return False
self._emit(SearchStarted(path=path, source=source.name))
cover = self._cover_search(
source, profile, series_pinned=source.name in online.lookup.series_ids
)
if self._write_cover_match(source, online, profile, path, cover.match):
return True
candidates, criteria_summary = self._run_search(source, profile, path)
if cover.candidates:
return self._resolve_with_cover_rows(
source, online, candidates or [], cover, path
)
return self._resolve_name_search(
source, online, candidates, criteria_summary, path
)
def _resolve_name_search(
self,
source: OnlineSource,
online: OnlineSettings,
candidates: list[Candidate] | None,
criteria_summary: str,
path: Path | None,
) -> bool:
"""Resolve the name search alone: a failure, nothing found, or a ranking."""
if candidates is None:
return False
if not candidates:
self._report_empty_search(source, criteria_summary, path)
return False
resolution = self._resolve_with_matcher(source.name, candidates, online)
return self._apply_resolution(source, resolution, path)
def _write_cover_match(
self,
source: OnlineSource,
online: OnlineSettings,
profile: ComicProfile,
path: Path | None,
match: CoverMatch | None,
) -> bool:
"""
Write the match a cover search's verdict accepted, if there is one.
Not under ``ask``, which never writes unprompted. Under every other
mode, ``careful`` included, the verdict is metron-tagger's
calibrated rule (see `cover_verdict`), which is stronger evidence
than the metadata score's "unambiguous" test those modes otherwise
write on.
False when there's nothing to write or the fetch failed; the name
search runs next, as it does after a series-cache hit whose fetch
fails.
"""
if match is None or resolve_match(online, source.name) is MatchMode.ASK:
return False
self._emit(
SearchCompleted(
path=path, source=source.name, n_candidates=match.n_candidates
)
)
candidate = match.candidate
return self._accept(
source,
candidate.issue_id,
outcome_stats.record_auto_write,
emit_auto_written=True,
candidate=candidate
if self._cover_match_may_seed_cache(profile, candidate)
else None,
)
def _resolve_with_cover_rows(
self,
source: OnlineSource,
online: OnlineSettings,
candidates: list[Candidate],
cover: CoverSearchResult,
path: Path | None,
) -> bool:
"""
Resolve the name search, offering the cover rows if it would prompt.
A name-search auto-write stands: cover rows never turn it into a
prompt. Anything else (a prompt, a skip, no match, nothing found or
a failed name search) ends at a prompt over both sets of rows, or a
skip under ``--prompts never``. The cover rows don't auto-write by
metadata score here; only the cover verdict writes on cover
evidence.
"""
if candidates:
resolution = self._resolve_with_matcher(source.name, candidates, online)
if resolution.kind is ResolutionKind.AUTO_WRITE:
return self._apply_resolution(source, resolution, path)
resolution = self._cover_prompt(
self._build_profile(), source.name, online, candidates, cover
)
return self._apply_resolution(source, resolution, path)
def _report_empty_search(
self, source: OnlineSource, criteria_summary: str, path: Path | None
) -> None:
"""
Say why a search produced nothing: a real miss, or no search at all.
A source that declined to search — today's quota is down to the
reserve that finishes comics which already matched — emits `Skipped`
carrying that reason. An embedding application needs the difference:
a comic nobody looked at should be tried again, while one the source
genuinely missed should not.
"""
# Optional capability, read structurally: a source is whatever
# implements search() and friends, and most never decline to search.
reason = getattr(source, "search_skip_reason", None)
if reason:
outcome_stats.record_skip(source.name)
self._emit(Skipped(path=path, source=source.name, reason=reason))
return
logger.info(
f"online {source.name}: 0 candidates for {criteria_summary} "
"(no matching issues in the database)"
)
def _emit_auto_written(self, source: OnlineSource, issue_id: int) -> None:
"""
Emit AutoWritten for a win, however the issue id was obtained.
Called only from `_accept`, and only once the fetch has landed, so
every auto-write — cold-path search, series-cache hit, ``--id``
pin, stored-id refresh — carries its source and path, and no
failed fetch announces one. Event consumers (e.g. Codex's status
table) need it on the fast paths too, or they can't attribute the
matched source for previously-tagged comics.
"""
self._emit(
AutoWritten(
path=getattr(self, "_path", None),
source=source.name,
candidate_summary=str(issue_id),
)
)
def _lookup_one_source(
self, source: OnlineSource, online: OnlineSettings
) -> _SourceOutcome:
"""
Drive the lookup for one source and report what it did.
Two facts come back, not one (see `_SourceOutcome`): whether
metadata was applied, and whether the source consumed a pinned
identity for this comic. The two pinned-id fast paths claim the
comic either way, so first-wins still keeps a sibling source from
fuzzy-matching behind a failed pin, but only a landed fetch
reports ``applied``.
"""
# Explicit --id is the strongest user signal. It overrides
# --rematch and the stored-id fast path.
explicit_ids = online.lookup.ids
issue_id = explicit_ids.get(source.name)
if issue_id is not None:
applied = self._accept(
source,
issue_id,
outcome_stats.record_explicit_id,
emit_auto_written=True,
)
return _SourceOutcome(applied=applied, claimed=True)
# Fast refresh: a stored upstream id from a prior tag lets us
# call source.get(id) instead of walking the full search path.
# ``--rematch`` suppresses the fast path so users can re-evaluate
# a stale/wrong stored id.
if not online.lookup.rematch:
stored_id = self._stored_identifier(source.name)
if stored_id is not None:
logger.info(
f"online {source.name}: refreshing via stored id={stored_id}"
)
applied = self._accept(
source,
stored_id,
outcome_stats.record_auto_write,
emit_auto_written=True,
)
return _SourceOutcome(applied=applied, claimed=True)
# Series-first batching fast path (plan §3.10). When the session
# has cached a resolved volume_id for this comic's series
# fingerprint, skip the expensive search and ask the source
# directly for "issue N in volume V." --rematch bypasses this
# path too (consistent with its "don't trust prior verdict"
# intent).
if not online.lookup.rematch and self._try_series_cache_lookup(source):
return _SourceOutcome(applied=True)
# Single-flight the cold search. Under `-j N` the first N files of
# a cluster start together, all miss the cache and all pay for the
# same search; whoever leads releases the rest, which then find
# the resolved id waiting for them.
key = self._series_lead_key(source, online)
try:
return _SourceOutcome(applied=self._search_path(source, online))
finally:
self._release_series_lead(key)
def _series_cache_key(self, source: OnlineSource) -> tuple[str, str] | None:
"""
Key this comic's series takes in the cache, or None if it has none.
A volume-scoped lookup needs an issue number to scope with.
Without one the source would list the whole series and accept
whatever row came first — a mis-tag plus unbounded pagination.
The search path already handles issue-less comics.
"""
if self._series_cache is None:
return None
profile = self._build_profile()
if not profile.series or not strip_issue_leading_zeros(profile.issue):
return None
return (source.name, _series_fingerprint(profile))
def _series_lead_key(
self, source: OnlineSource, online: OnlineSettings
) -> tuple[str, str] | None:
"""
Take leadership of this comic's series before a cold search, if free.
Returns the key to release afterwards, or None when there is
nothing to lead — no cache, no usable key, `--rematch` (every file
re-searches by definition), a plain dict (a sequential caller
cannot race anyway), or another worker already leading. That last
case is not a problem: the other worker holds a *different*
series, or this comic already waited for it in
`_try_series_cache_lookup` and came back unresolved.
"""
cache = self._series_cache
if cache is None or online.lookup.rematch:
return None
key = self._series_cache_key(source)
if key is None or not lead_series(cache, key):
return None
return key
def _release_series_lead(self, key: tuple[str, str] | None) -> None:
"""Hand leadership back after a cold search, however it ended."""
if key is not None and self._series_cache is not None:
release_series(self._series_cache, key)
def _try_series_cache_lookup(self, source: OnlineSource) -> bool:
"""
Attempt the volume-scoped issue lookup; return True on hit + accept.
Cache miss, missing issue number, source-side failure, or a
stale-cache "issue not in this volume" response → return False so
the caller falls through to the cold-path search. The cache entry
is left alone in that case (first-writer-wins).
A miss with another worker already resolving this same series
WAITS for it instead of racing it. That is the whole value of
series batching under `-j N`: without it the first N files of a
cluster all start cold, and the plan's measured "one search per
series" collapses back to "one search per worker".
"""
key = self._series_cache_key(source)
if key is None or self._series_cache is None:
return False
volume_id = self._series_cache.get(key)
if volume_id is None:
# Another worker may be resolving this very series; waiting
# for it is the whole value of batching under `-j N`.
await_series_leader(self._series_cache, key)
volume_id = self._series_cache.get(key)
if volume_id is None:
return False
profile = self._build_profile()
try:
candidate = source.lookup_issue(volume_id, profile.issue)
except NotImplementedError:
# Source hasn't implemented the fast path — fall through.
return False
except OnlineLookupAbortedError:
raise
except Exception as exc:
logger.warning(
f"online {source.name}: series-cache lookup_issue "
f"(volume_id={volume_id}, number={profile.issue!r}) "
f"failed: {exc}; falling back to search"
)
return False
if candidate is None:
logger.info(
f"online {source.name}: cached volume_id={volume_id} "
f"returned no match for issue#={profile.issue!r}; "
"falling back to search (cache entry preserved)"
)
return False
logger.info(
f"online {source.name}: series-cache hit; accepted "
f"id={candidate.issue_id} via volume_id={volume_id}"
)
return self._accept_candidate(source, candidate)
def _first_normalized(self, src: MetadataSources) -> dict | None:
"""First normalized metadata dict from `src`, or None if unset."""
normalized = self.get_normalized_metadata(src)
if not normalized:
return None
for loaded in normalized:
md = dict(loaded.metadata)
if md:
return md
return None
def _cross_source_cv_id_check(self) -> None:
"""
Warn when Metron's stored `cv_id` and our CV match disagree.
Runs once per box after both online sources have been queried.
The check looks at the per-source normalized metadata (still
distinguishable here, before the box-level merge keeps Comic
Vine's own `comicbox.identifiers.comicvine.key` over Metron's
cross-reference). Neither is known to be right, so surface the
disagreement for the user to check.
"""
metron_md = self._first_normalized(MetadataSources.METRON_API)
cv_md = self._first_normalized(MetadataSources.COMICVINE_API)
disagreement = _detect_cv_id_disagreement(metron_md, cv_md)
if disagreement is None:
return
metron_id, cv_id = disagreement
logger.warning(
f"online: cross-source ComicVine id disagreement — Metron "
f"stored cv_id={metron_id} but our independent ComicVine "
f"match returned id={cv_id}. One of the two sources has the "
f"wrong identifier; review before accepting."
)
def _should_skip_first_wins(
self, source: OnlineSource, online: OnlineSettings, *, satisfied: bool
) -> bool:
"""
First-wins skip; explicit-id sources always run.
``satisfied`` means an earlier source either applied metadata or
claimed the comic with a pinned id. The claim half is what keeps a
failed ``--id`` fetch from handing the comic to a sibling source's
fuzzy search.
"""
if not satisfied or not online.lookup.first_wins:
return False
has_explicit = (
source.name in online.lookup.ids or source.name in online.lookup.series_ids
)
return not has_explicit
def _run_active_sources(
self,
active_sources: list[OnlineSource],
online: OnlineSettings,
path: Path | None,
) -> bool:
"""
Query each source in order; return whether any applied metadata.
``satisfied`` accumulates both halves of `_SourceOutcome` because
first-wins stops on either one, while only ``applied`` is reported
back to the caller.
"""
applied_any = False
satisfied = False
for source in active_sources:
if self._should_skip_first_wins(source, online, satisfied=satisfied):
logger.info(
f"online {source.name}: skipped (first-wins satisfied; "
f"use --all-sources to query every source)"
)
continue
# After the first-wins skip, so a source that sat out never
# claims to be running. Covers every route _lookup_one_source
# can take, including the explicit-id, stored-id and
# series-cache fast paths that never reach a SearchStarted.
self._emit(SourceStarted(path=path, source=source.name))
outcome = self._lookup_one_source(source, online)
applied_any = applied_any or outcome.applied
satisfied = satisfied or outcome.applied or outcome.claimed
return applied_any
def run_online_lookup(self) -> bool:
"""
Idempotent: populate online MetadataSources once per box instance.
Returns whether online metadata was actually applied to this box.
A repeat call returns the first run's outcome. ``False`` means the
comic's metadata is unchanged (disabled, no sources, no match,
skipped, deferred prompt, or a pinned-id fetch that failed), so
callers can avoid pointless re-writes of existing tags.
A source claiming the comic via a pinned id is deliberately *not*
folded into this return value; it only gates the first-wins skip
below. Reporting "applied" for a claim is what let a failed
``--id`` fetch surface as ``written``.
The lookup policy is read once here and threaded down, so the
whole file resolves under one generation even while a sibling
``-j N`` worker is answering a prompt that changes it. The one
exception is the prompt loop, which re-reads on purpose so the
answer applies to the candidates being asked about.
"""
if self._online_lookup_already_done():
return self._online_lookup_won
self._mark_online_lookup_done()
online = self._session_online()
path = getattr(self, "_path", None)
if not online.lookup.enabled:
return False
if online.lookup.prompts is not Prompts.NEVER:
_no_tty_hint.maybe_log(has_callback=self._online_selector is not None)
active_sources = self._build_active_online_sources(online)
if not active_sources and online.lookup.sources is None:
logger.warning(
"online: --online all requested but no sources are configured "
"(no credentials available for any known source)"
)
applied_any = self._run_active_sources(active_sources, online, path)
self._online_lookup_won = applied_any
self._cross_source_cv_id_check()
self._emit(
FileFinished(path=path, outcome="written" if applied_any else "no_change")
)
return applied_any
|