Skip to content

comicbox.online_session

OnlineSession — Codex-facing API for batch online metadata tagging.

Wraps the existing Comicbox.run_online_lookup() per-file flow with a Codex-friendly surface:

  • Per-source credential validation up front (fail-fast).
  • Direct :class:MatchMode API (no string alias layer; ASK needs a PromptHandler or defer_prompts=True, since the session has no built-in prompt resolver of its own).
  • One programmatic PromptHandler per session that the matcher calls whenever it would otherwise hit the CLI questionary prompt.
  • Event stream via on_event= for UI feedback.
  • Cancellation token: callers stop the batch between files.

The internal matcher / selector / rate-limit machinery is untouched; this module is a façade.

BatchedPromptHandler

Bases: Protocol

A PromptHandler that also supports batched prompt delivery.

Codex’s defer-mode UI naturally yields a window of prompts the user will resolve together. When the engine gains the per-session prompt queue (step 8), it will prefer request_many over request for handlers structurally matching this Protocol.

Source code in comicbox/online_session.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@runtime_checkable
class BatchedPromptHandler(Protocol):
    """
    A PromptHandler that also supports batched prompt delivery.

    Codex's defer-mode UI naturally yields a window of prompts the user
    will resolve together. When the engine gains the per-session prompt
    queue (step 8), it will prefer ``request_many`` over ``request`` for
    handlers structurally matching this Protocol.
    """

    def request(self, prompt: OnlinePrompt) -> PromptResponse:
        """Resolve one prompt; return the chosen action/payload."""
        ...

    def request_many(self, prompts: Sequence[OnlinePrompt]) -> Sequence[PromptResponse]:
        """
        Resolve a window of prompts in one call.

        Return one response per prompt, in the same order. The engine
        will not interleave ``request`` and ``request_many`` calls
        within a single drain window.
        """
        ...

request(prompt)

Resolve one prompt; return the chosen action/payload.

Source code in comicbox/online_session.py
211
212
213
def request(self, prompt: OnlinePrompt) -> PromptResponse:
    """Resolve one prompt; return the chosen action/payload."""
    ...

request_many(prompts)

Resolve a window of prompts in one call.

Return one response per prompt, in the same order. The engine will not interleave request and request_many calls within a single drain window.

Source code in comicbox/online_session.py
215
216
217
218
219
220
221
222
223
def request_many(self, prompts: Sequence[OnlinePrompt]) -> Sequence[PromptResponse]:
    """
    Resolve a window of prompts in one call.

    Return one response per prompt, in the same order. The engine
    will not interleave ``request`` and ``request_many`` calls
    within a single drain window.
    """
    ...

DeferredPrompt dataclass

A prompt the session skipped under defer_prompts mode.

Captures everything Codex needs to render the prompt later in a review-tagging UI: the file it came from, source, candidates, match context, and the fingerprint used to key the dedup cache. Codex feeds the user’s resolution back via :meth:OnlineSession.preload_resolution.

Source code in comicbox/online_session.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
@dataclass(frozen=True, slots=True)
class DeferredPrompt:
    """
    A prompt the session skipped under defer_prompts mode.

    Captures everything Codex needs to render the prompt later in a
    review-tagging UI: the file it came from, source, candidates, match
    context, and the fingerprint used to key the dedup cache. Codex
    feeds the user's resolution back via :meth:`OnlineSession.preload_resolution`.
    """

    path: Path | None
    source: str
    fingerprint: str
    profile_summary: dict[str, Any]
    candidates: tuple[Candidate, ...]
    match: MatchMode
    prompts: Prompts

Effort

Bases: StrEnum

API-call effort per comic, for fan-out sources.

Orthogonal to MatchMode (which controls how the matcher’s verdict is applied). Effort controls how aggressively pre-call algorithms trade accuracy for API throughput — it only bites on sources that fan out per candidate (ComicVine). Single-call sources (Metron since PR #143) have no fan-out to throttle and ignore it.

  • MINIMAL: aggressive pre-filtering; trade accuracy for throughput.
  • BALANCED: today’s behavior; the default.
  • THOROUGH: spend API budget freely; max accuracy.
Source code in comicbox/config/online/settings.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Effort(StrEnum):
    """
    API-call effort per comic, for fan-out sources.

    Orthogonal to ``MatchMode`` (which controls how the matcher's
    verdict is applied). ``Effort`` controls how aggressively pre-call
    algorithms trade accuracy for API throughput — it only bites on
    sources that fan out per candidate (ComicVine). Single-call sources
    (Metron since PR #143) have no fan-out to throttle and ignore it.

    - ``MINIMAL``: aggressive pre-filtering; trade accuracy for throughput.
    - ``BALANCED``: today's behavior; the default.
    - ``THOROUGH``: spend API budget freely; max accuracy.
    """

    MINIMAL = "minimal"
    BALANCED = "balanced"
    THOROUGH = "thorough"

MatchMode

Bases: StrEnum

Match-resolution aggressiveness.

Strictly increasing aggressiveness: each level auto-writes a superset of what the previous one does (ask ⊂ careful ⊂ auto ⊂ eager). See match-resolution-user-doc.md for the full decision algorithm.

A StrEnum so dataclass equality, dict keys, JSON serialization, and str() all “just work”.

Source code in comicbox/config/online/settings.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class MatchMode(StrEnum):
    """
    Match-resolution aggressiveness.

    Strictly increasing aggressiveness: each level auto-writes a
    superset of what the previous one does (ask ⊂ careful ⊂ auto ⊂
    eager). See ``match-resolution-user-doc.md`` for the full
    decision algorithm.

    A StrEnum so dataclass equality, dict keys, JSON serialization, and
    ``str()`` all "just work".
    """

    ASK = "ask"
    CAREFUL = "careful"
    AUTO = "auto"
    EAGER = "eager"

OnlineConfigurationError

Bases: ComicboxError

Raised when OnlineSession inputs are inconsistent or incomplete.

Source code in comicbox/exceptions.py
132
133
class OnlineConfigurationError(ComicboxError):
    """Raised when OnlineSession inputs are inconsistent or incomplete."""

OnlineCredentials dataclass

Credentials for the online sources Codex may enable.

Source code in comicbox/online_session.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
@dataclass(frozen=True, slots=True)
class OnlineCredentials:
    """Credentials for the online sources Codex may enable."""

    metron_key: str | None = None
    metron_url: str | None = None
    comicvine_key: str | None = None
    comicvine_url: str | None = None
    versedb_key: str | None = None
    versedb_url: str | None = None

    def key_for(self, source: str) -> str | None:
        """Return the key, or token, for ``source``."""
        return getattr(self, f"{source}_key", None)

    def url_for(self, source: str) -> str | None:
        """Return the API url override for ``source``."""
        return getattr(self, f"{source}_url", None)

key_for(source)

Return the key, or token, for source.

Source code in comicbox/online_session.py
133
134
135
def key_for(self, source: str) -> str | None:
    """Return the key, or token, for ``source``."""
    return getattr(self, f"{source}_key", None)

url_for(source)

Return the API url override for source.

Source code in comicbox/online_session.py
137
138
139
def url_for(self, source: str) -> str | None:
    """Return the API url override for ``source``."""
    return getattr(self, f"{source}_url", None)

OnlinePrompt dataclass

Codex-facing handoff for an ambiguous match.

The PromptHandler receives one of these and returns a PromptResponse.

Source code in comicbox/online_session.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@dataclass(frozen=True, slots=True)
class OnlinePrompt:
    """
    Codex-facing handoff for an ambiguous match.

    The PromptHandler receives one of these and returns a PromptResponse.
    """

    path: Path | None
    source: str
    profile_summary: dict[str, Any]
    candidates: tuple[Candidate, ...]
    match: MatchMode
    prompts: Prompts

OnlineResult dataclass

Per-file outcome of an online tagging call.

tags is the file’s full merged metadata, present even when the lookup applied nothing new (skip, no-match, deferred prompt) — it is NOT evidence of a match. matched is: it’s True only when an online source actually contributed metadata, so writers should gate on it to avoid re-writing a file with its own existing tags.

Source code in comicbox/online_session.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
@dataclass(frozen=True, slots=True)
class OnlineResult:
    """
    Per-file outcome of an online tagging call.

    ``tags`` is the file's full merged metadata, present even when the
    lookup applied nothing new (skip, no-match, deferred prompt) — it is
    NOT evidence of a match. ``matched`` is: it's True only when an
    online source actually contributed metadata, so writers should gate
    on it to avoid re-writing a file with its own existing tags.
    """

    path: Path
    tags: dict[str, Any] | None = None
    error: BaseException | None = None
    cancelled: bool = False
    matched: bool = False

OnlineSession

Codex-friendly façade over Comicbox’s online lookup.

Construction validates per-source credentials and pre-computes the ComicboxSettings layer that each per-file Comicbox instance will see. Mutable state — the lookup policy (match / prompts) and the cancel token — lives on the instance and may be updated from any thread. The policy lives in an OnlineSessionState shared with every box the session spawns, so a change made at a prompt needs no mirroring back: the box and the session read the same owner.

sources is ordered, and its order is both run priority and merge precedence: the first source runs first and, under first_wins, its match ends the lookup; with first_wins off every source runs and the first one wins every tag they disagree on, except that each source keeps its own id: Comic Vine’s id beats Metron’s cv_id cross-reference to it.

ids pins an issue id per source for a single-comic session: a pinned source fetches that id directly while the unpinned sources search, so one run can mix id retrieval and search and merge both.

config supplies the settings the session layers its tagging preferences over. An embedder that already holds configured ComicboxSettings — naming its own cache directory or effort, neither of which an OnlineSession keyword covers — passes them here instead of exporting environment variables for the settings loader to find. Omitted, the session reads config files and the environment itself.

Source code in comicbox/online_session.py
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
class OnlineSession:
    """
    Codex-friendly façade over Comicbox's online lookup.

    Construction validates per-source credentials and pre-computes the
    ComicboxSettings layer that each per-file Comicbox instance will see.
    Mutable state — the lookup policy (``match`` / ``prompts``) and the
    cancel token — lives on the instance and may be updated from any
    thread. The policy lives in an ``OnlineSessionState`` shared with
    every box the session spawns, so a change made at a prompt needs no
    mirroring back: the box and the session read the same owner.

    ``sources`` is ordered, and its order is both run priority and merge
    precedence: the first source runs first and, under ``first_wins``,
    its match ends the lookup; with ``first_wins`` off every source runs
    and the first one wins every tag they disagree on, except that each
    source keeps its own id: Comic Vine's id beats Metron's ``cv_id``
    cross-reference to it.

    ``ids`` pins an issue id per source for a single-comic session: a
    pinned source fetches that id directly while the unpinned sources
    search, so one run can mix id retrieval and search and merge both.

    ``config`` supplies the settings the session layers its tagging
    preferences over. An embedder that already holds configured
    ``ComicboxSettings`` — naming its own cache directory or effort,
    neither of which an ``OnlineSession`` keyword covers — passes them
    here instead of exporting environment variables for the settings
    loader to find. Omitted, the session reads config files and the
    environment itself.
    """

    def __init__(  # noqa: PLR0913
        self,
        *,
        # VerseDB is opt-in: naming it needs a `versedb_key`, so adding it
        # here would fail every existing caller's credential check.
        sources: Iterable[str] = ("metron", "comicvine"),
        ids: Mapping[str, int] | None = None,
        credentials: OnlineCredentials | None = None,
        match: MatchMode = MatchMode.AUTO,
        prompts: Prompts = Prompts.ASK,
        prompt_handler: PromptHandler | None = None,
        on_event: EventHandler | None = None,
        rematch: bool = False,
        first_wins: bool = True,
        defer_prompts: bool = False,
        series_batching: bool = True,
        config: ComicboxSettings | None = None,
        client_name: str | None = None,
    ) -> None:
        """Validate inputs, build per-session state. See class docstring."""
        # Identify the embedding application in the outgoing User-Agent.
        # Metron's operators cannot otherwise tell a library embedder —
        # which may be running several processes against one token, each
        # with its own rate gate — from the CLI's single-process thread
        # pool. Set before any source builds its client, since clients
        # bake the header in at construction.
        set_user_agent_context("lib", client=client_name)
        # Order is run priority and merge precedence; see the class
        # docstring.
        self._sources = tuple(dict.fromkeys(sources))
        self._validate_sources(self._sources)
        # Pinned per-source issue ids. A source with an id fetches it
        # directly; the rest of the sources search as usual, so one session
        # can mix id retrieval and search and merge both results.
        self._ids: dict[str, int] = dict(ids or {})
        self._validate_ids(self._sources, self._ids)
        self._credentials = credentials or OnlineCredentials()
        self._validate_credentials(self._sources, self._credentials)
        # The prompt resolvers come before the match mode: whether ASK
        # is acceptable depends on having one.
        self._prompt_handler = prompt_handler
        self._defer_prompts = defer_prompts
        self._state = OnlineSessionState(
            match=self._validate_match(match),
            prompts=prompts,
        )
        self._on_event = on_event
        self._rematch = rematch
        self._first_wins = first_wins
        self._series_batching = series_batching
        # Read config files / env exactly once per session. _build_config
        # used to call get_config() per file — wasted disk I/O on big
        # batches plus a behavioral surprise where a config-file edit
        # mid-batch changed settings for the remaining files. A caller
        # that passes its own settings skips the read entirely: they are
        # already the answer this would have gone looking for.
        self._base_settings: ComicboxSettings = (
            config if config is not None else get_config()
        )
        # Nothing in the settings tree varies per file: the mutable
        # policy lives in _state and each box overlays it for itself.
        self._settings: ComicboxSettings = self._build_config()

        # Cancel token. Set when cancel() is called; checked between files
        # in tag_many() and consulted by the wired retry sleep
        # (_retry_sleep_wait), which aborts an in-flight rate-limit wait.
        self._cancel = threading.Event()

        # Prompt-dedup cache. Keyed by fingerprint of (source, normalized
        # series, sorted distinct candidate volume_ids); the stored entry
        # is the PromptResponse the handler returned the first time we
        # saw this fingerprint. For "choose" actions we also record the
        # candidate's volume_id so we can re-map the index when the new
        # prompt's candidate list is ordered differently. Per-session,
        # in-memory only — disk persistence is out of scope for v1.
        self._prompt_cache: dict[str, _CachedResolution] = {}
        self._prompt_cache_lock = threading.Lock()

        # Defer-prompts queue. When ``defer_prompts`` is set, the bridged
        # selector skips the user's PromptHandler and queues the prompt
        # here instead. Codex's flow: drain via ``deferred_prompts()`` at
        # end-of-batch, present in a review UI, then seed resolutions
        # back via ``preload_resolution()`` and re-run the affected files.
        self._deferred: list[DeferredPrompt] = []
        self._deferred_lock = threading.Lock()

        # Series cache (plan §3.10). Keyed by (source_name, series
        # fingerprint); value is the resolved volume_id. Populated by
        # the matcher on each cold-path acceptance; consulted before the
        # cold-path search on subsequent comics of the same series so
        # we make one `search` call per series instead of one per issue.
        # In-memory only per the resolved open question.
        self._series_cache: dict[tuple[str, str], int] = {}
        self._series_cache_lock = threading.Lock()
        # How many comics of each series the current `tag_many` batch
        # holds, by filename fingerprint. Empty for single-file `tag()`,
        # which clusters nothing.
        self._series_cluster_sizes: Counter[str] = Counter()
        # Why a lookup aborted the run, if one did. See `abort_reason`.
        self._abort_reason: str | None = None

    # -- mutable session state ----------------------------------------------

    @property
    def match(self) -> MatchMode:
        """
        Current session match mode (read-only; mutate via set_match()).

        ``set_match`` accepts ``MatchMode.ASK`` only while a prompt
        handler or deferred prompts can resolve the prompts it raises.
        A selector answering ``set_policy: "ask"`` sets it without that
        check, so this may report ASK where ``set_match`` would refuse.
        """
        return self._state.snapshot().match

    @property
    def prompts(self) -> Prompts:
        """Current session prompt policy."""
        return self._state.snapshot().prompts

    def set_match(self, match: MatchMode) -> None:
        """
        Change the session match mode for subsequent file lookups.

        ``MatchMode.ASK`` prompts for every match, so it is accepted only
        while the session has a prompt handler or defers its prompts.
        """
        self._state.set_match(self._validate_match(match))

    def set_prompts(self, prompts: Prompts) -> None:
        """Change the session prompt policy for subsequent file lookups."""
        self._state.set_prompts(prompts)

    def cancel(self) -> None:
        """Stop accepting new files. In-flight lookup runs to completion."""
        self._cancel.set()

    def close(self) -> None:
        """
        Release the pooled connections and cache handles every source holds.

        Optional, and not a cancel: the session stays usable afterwards,
        at the cost of reopening what it needs on its next request. The
        upstream clients are process-wide per credential set, so closing
        while another `OnlineSession` in the same process is mid-run
        costs that run the same reopen. Acceptable, and the alternative
        -- leaving the sockets and sqlite handles to be finalized -- is
        what emits `ResourceWarning`.

        Comic Vine is the one sharp edge: its rate-limit buckets are
        closed with the session, so a lookup already holding one can fail
        outright rather than merely reconnect. Close between files, not
        under one.
        """
        from comicbox.formats.comicvine_api.online_source import (
            close_shared_sessions as close_comicvine,
        )
        from comicbox.formats.metron_api.online_source import (
            close_shared_sessions as close_metron,
        )
        from comicbox.formats.versedb_api.online_source import (
            close_shared_sessions as close_versedb,
        )

        close_metron()
        close_comicvine()
        close_versedb()

    def __enter__(self) -> Self:
        """Enter the context manager, returning this session."""
        return self

    def __exit__(self, *_exc_info: object) -> None:
        """Exit the context manager, releasing pooled connections."""
        self.close()

    @property
    def cancelled(self) -> bool:
        """Whether cancel() has been called."""
        return self._cancel.is_set()

    @property
    def abort_reason(self) -> str | None:
        """
        Why the session stopped itself, or None if nobody's lookup aborted.

        None after a plain :meth:`cancel` — that is the caller's own doing
        and needs no explanation. Set when a lookup raised
        `OnlineLookupAbortedError`, most usefully when the day's API quota
        ran out, which stops a run the caller never asked to stop.
        """
        return self._abort_reason

    # -- deferred prompts ---------------------------------------------------

    @property
    def defer_prompts(self) -> bool:
        """Whether the session is currently in defer-prompts mode."""
        return self._defer_prompts

    def set_defer_prompts(self, *, defer: bool) -> None:
        """
        Toggle defer-prompts mode for subsequent file lookups.

        Turning deferral off leaves the match mode alone, even when it
        is ``MatchMode.ASK`` and no prompt handler is set. The ASK guard
        in the constructor and ``set_match`` is an entry check, not an
        invariant this toggle re-enforces: a session left in ASK without
        a resolver prompts for every match, and each lookup reports the
        missing resolver at prompt time, as for any session without one.
        """
        self._defer_prompts = defer

    def deferred_prompts(self) -> tuple[DeferredPrompt, ...]:
        """Snapshot the queued deferred prompts. Codex's review-UI input."""
        with self._deferred_lock:
            return tuple(self._deferred)

    def clear_deferred_prompts(self) -> None:
        """Drop the deferred-prompt queue without resolving them."""
        with self._deferred_lock:
            self._deferred.clear()

    def preload_resolution(
        self,
        fingerprint: str,
        *,
        action: Literal["choose", "skip", "manual"],
        payload: int | str | None = None,
        chosen_volume_id: int | None = None,
    ) -> None:
        """
        Seed the dedup cache so a re-run auto-resolves the fingerprint.

        Codex's defer-mode flow: drain ``deferred_prompts()`` after the
        batch, present them in a review UI, call ``preload_resolution()``
        for each one the user resolves, then re-tag the affected files
        (with defer_prompts toggled off if desired). The cache hit fires
        the same way it does for in-batch dedup. A non-empty cache is
        enough to install the bridged selector — but with no handler and
        defer_prompts off, a cache MISS (the re-search produced a
        different candidate set than the fingerprint was minted from)
        raises rather than falling back to the interactive CLI prompt.
        """
        entry = _CachedResolution(
            action=action, payload=payload, chosen_volume_id=chosen_volume_id
        )
        with self._prompt_cache_lock:
            self._prompt_cache[fingerprint] = entry

    # -- series-first batching ----------------------------------------------

    def preload_series_resolution(
        self, *, source: str, series_fingerprint: str, volume_id: int
    ) -> None:
        """
        Seed the series cache from outside the session.

        Codex's use case: persist resolved series across runs in its own
        DB and replay them at session-start to skip the cold-path search
        entirely on subsequent imports. Same first-writer-wins semantic
        as in-batch population — if the key is already cached, this is
        a no-op.
        """
        key = (source, series_fingerprint)
        with self._series_cache_lock:
            self._series_cache.setdefault(key, volume_id)

    def series_cache_snapshot(self) -> dict[tuple[str, str], int]:
        """Snapshot the current series cache. Useful for persistence."""
        with self._series_cache_lock:
            return dict(self._series_cache)

    def clear_series_cache(self) -> None:
        """Drop every series resolution from the cache."""
        with self._series_cache_lock:
            self._series_cache.clear()

    # -- rate limits --------------------------------------------------------

    def rate_limit_status(self) -> dict[str, dict[str, Any]]:
        """
        Snapshot of each enabled source's current rate-limit budget.

        Every entry maps a window name to a JSON-safe
        ``limit`` / ``remaining`` / ``reset_epoch`` triple, so one
        renderer handles every source; only the window names differ,
        because the services meter differently.

        Metron carries the live per-account state mokkari>=4 tracks from
        ``X-RateLimit-*`` response headers::

            {"burst": {"limit": 20, "remaining": 19, "reset_epoch": ...},
             "sustained": {"limit": 5000, "remaining": 4987, "reset_epoch": ...}}

        The sustained (daily) limit varies by Metron OpenCollective donor
        tier, so it is only discoverable from these headers.

        Comic Vine meters per resource, so it reports one window per
        endpoint pool it has actually used::

            {"issues": {"limit": 200, "remaining": 197, "reset_epoch": ...},
             "search": {"limit": 200, "remaining": 199, "reset_epoch": ...}}

        Its numbers are read from the rate-limit bucket file rather than
        from a live client, so they survive across runs and are available
        before this session issues a request. ``reset_epoch`` is when the
        window's oldest request ages out and frees the next slot.

        VerseDB meters per account per hour, and reports the window its
        shared client last saw in ``X-RateLimit-*``. It sends no reset
        time, so ``reset_epoch`` is None; the 4,000-a-day cap of its free
        tier has no header at all::

            {"hour": {"limit": 300, "remaining": 287, "reset_epoch": None}}

        A source reports ``{}`` until it has data: for Metron that means
        no request has gone out yet in this process (no shared session,
        or no header seen); for Comic Vine, that no bucket file exists
        yet or it could not be read; for VerseDB, that no shared client
        has had a response yet.
        """
        statuses: dict[str, dict[str, Any]] = {name: {} for name in self._sources}
        if "metron" in statuses:
            from comicbox.formats.metron_api.online_source import (
                shared_session_rate_limit_status,
            )

            status = shared_session_rate_limit_status(self._credentials.metron_key)
            if status is not None:
                statuses["metron"] = _rate_limit_windows(status)
        if "comicvine" in statuses:
            from comicbox.formats.comicvine_api.online_source import (
                shared_client_rate_limit_status,
            )

            statuses["comicvine"] = shared_client_rate_limit_status(
                self._settings.online
            )
        if "versedb" in statuses:
            from comicbox.formats.versedb_api import online_source as versedb

            statuses["versedb"] = versedb.shared_client_rate_limit_status(
                self._credentials.versedb_key, self._credentials.versedb_url
            )
        return statuses

    # -- per-file tagging ---------------------------------------------------

    def tag(self, path: Path) -> OnlineResult:
        """Tag one file synchronously."""
        if self._cancel.is_set():
            return OnlineResult(path=path, cancelled=True)
        try:
            tags, matched = self._run_one(path)
        except OnlineLookupAbortedError as exc:
            # The handler answered "abort", a cancelled retry sleep aborted
            # an in-flight lookup, or the day's API quota ran out. Abort
            # means "abort the entire run", not "skip this file": trip the
            # cancel token so tag_many drains the remaining paths as
            # cancelled.
            #
            # Keep the reason. Every path out of here looks identical to a
            # caller — a stream of cancelled results — but "the user paused
            # it" and "Metron has nothing left today" call for different
            # handling, and the second has to be readable without scraping
            # the log.
            self._abort_reason = str(exc)
            logger.warning(f"online: lookup aborted: {exc}")
            self.cancel()
            return OnlineResult(path=path, cancelled=True)
        except Exception as exc:
            if self._on_event is not None:
                self._on_event(FileError(path=path, error=str(exc)))
            return OnlineResult(path=path, error=exc)
        return OnlineResult(path=path, tags=tags, matched=matched)

    def tag_many(self, paths: Iterable[Path]) -> Iterator[OnlineResult]:
        """
        Tag many files sequentially. Stops accepting new ones on cancel.

        When ``series_batching`` is on (the default), paths are reordered
        upfront by a lightweight filename-derived fingerprint so issues of
        the same series cluster together. The first issue of each cluster
        triggers the cold-path search; the remaining issues hit the
        per-session series cache and skip the search entirely. Order
        within a cluster is the original input order; the cluster order
        itself is deterministic (sorted by fingerprint) so re-runs
        produce identical cache-key sequences.

        Counting each cluster up front also lets the source that resolves
        a series decide to list the whole thing once rather than once per
        comic (`OnlineSource.prefetch_volume`) — worth the most here,
        where the run is sequential and every saved request is saved wall
        clock too.
        """
        path_list = list(paths)
        if self._series_batching:
            path_list = sorted(path_list, key=filename_series_fingerprint)
            self._series_cluster_sizes = Counter(
                filename_series_fingerprint(path) for path in path_list
            )
        for path in path_list:
            if self._cancel.is_set():
                yield OnlineResult(path=path, cancelled=True)
                continue
            yield self.tag(path)

    # -- internals ----------------------------------------------------------

    def _run_one(self, path: Path) -> tuple[dict[str, Any], bool]:
        with Comicbox(path, config=self._settings) as cb:
            # Bridge the selector when we have a handler, when defer
            # mode is on (defer produces no handler call but still needs
            # to intercept the prompt to queue it), or when resolutions
            # were preloaded — the bridged selector is the only consumer
            # of the prompt cache, so a preload-only replay session
            # (codex's resolve flow) needs it too.
            if (
                self._prompt_handler is not None
                or self._defer_prompts
                or self._prompt_cache
            ):
                cb.set_online_selector(self._bridged_selector())
            if self._on_event is not None:
                cb.set_event_handler(self._on_event)
            if self._series_batching:
                cb.set_series_cache(self._series_cache)
                cb.set_series_cluster_size(
                    self._series_cluster_sizes.get(filename_series_fingerprint(path), 1)
                )
            cb.set_retry_sleep(self._retry_sleep_wait)
            cb.set_online_session_state(self._state)
            matched = cb.run_online_lookup()
            payload = cb.to_dict()
        return payload.get("comicbox", {}), matched

    def _retry_sleep_wait(self, delay: float) -> None:
        """
        Wait out a retry delay, aborting the lookup when cancel() fires.

        Rate-limit recovery can sleep for minutes per attempt; plain
        time.sleep would make cancel() wait out the whole budget while
        the archive sits open. Waiting on the cancel event instead lets
        a caller interrupt mid-retry; raising aborts the in-flight
        lookup, which tag() converts into a cancelled result.
        """
        if self._cancel.wait(delay):
            reason = "online: session cancelled during retry wait"
            raise OnlineLookupAbortedError(reason)

    def _bridged_selector(self) -> Callable[..., SelectorResult]:
        """
        Adapt the user's PromptHandler into a SelectorCallback.

        Translates Comicbox's positional SelectorCallback signature into
        a Codex-facing OnlinePrompt / PromptResponse pair. Consults the
        per-session prompt cache first; on cache miss falls through to
        defer-mode (queue + skip) or the user's handler, depending on
        ``defer_prompts``. Resolutions from the handler path are stored
        for next time.
        """
        handler = self._prompt_handler

        def _selector(
            profile: ComicProfile,
            candidates: Sequence[Candidate],
            ctx: SelectorContext,
        ) -> SelectorResult:
            cand_tuple = tuple(candidates)
            fingerprint = _prompt_fingerprint(ctx.source, profile, cand_tuple)
            cached = self._lookup_cached_prompt(fingerprint, cand_tuple)
            if cached is not None:
                if self._on_event is not None:
                    self._on_event(
                        PromptResolvedFromCache(
                            path=ctx.file_path,
                            source=ctx.source,
                            prompt_id=f"{ctx.source}:{id(candidates)}",
                            action=cached[0],
                            fingerprint=fingerprint,
                        )
                    )
                return cached
            # Past the cache, the prompt will reach a person, so this is
            # where a source may spend a request on display detail. The
            # fingerprint above and the stored resolution below key on
            # volume ids, which enrichment leaves alone.
            if self._defer_prompts:
                enriched = ctx.enrich_candidates(cand_tuple)
                self._defer_prompt(fingerprint, profile, enriched, ctx)
                return ("skip", None)
            if handler is None:
                msg = (
                    "OnlineSession has no PromptHandler and defer_prompts "
                    "is disabled; cannot resolve an ambiguous match"
                )
                raise RuntimeError(msg)
            cand_tuple = ctx.enrich_candidates(cand_tuple)
            policy = self._state.snapshot()
            prompt = OnlinePrompt(
                path=ctx.file_path,
                source=ctx.source,
                profile_summary=_summarise_profile(profile),
                candidates=cand_tuple,
                match=policy.match,
                prompts=policy.prompts,
            )
            response = handler.request(prompt)
            # No session-state sync here: the box applies set_policy /
            # set_prompts to the OnlineSessionState this session shares
            # with it, so the change is already ours.
            self._store_prompt_resolution(fingerprint, response, cand_tuple)
            return (response.action, response.payload)

        return _selector

    def _defer_prompt(
        self,
        fingerprint: str,
        profile: ComicProfile,
        candidates: tuple[Candidate, ...],
        ctx: SelectorContext,
    ) -> None:
        """Queue this prompt for later resolution and emit PromptDeferred."""
        policy = self._state.snapshot()
        deferred = DeferredPrompt(
            path=ctx.file_path,
            source=ctx.source,
            fingerprint=fingerprint,
            profile_summary=_summarise_profile(profile),
            candidates=candidates,
            match=policy.match,
            prompts=policy.prompts,
        )
        with self._deferred_lock:
            self._deferred.append(deferred)
        if self._on_event is not None:
            self._on_event(
                PromptDeferred(
                    path=ctx.file_path,
                    source=ctx.source,
                    prompt_id=f"{ctx.source}:{id(candidates)}",
                    fingerprint=fingerprint,
                    n_candidates=len(candidates),
                )
            )

    def _lookup_cached_prompt(
        self, fingerprint: str, candidates: tuple[Candidate, ...]
    ) -> SelectorResult | None:
        """
        Match a fingerprint against the cache and re-map the choice.

        For ``choose`` we re-map the cached volume_id to whichever candidate
        in this prompt's list shares it. If no candidate matches, treat
        this as a cache miss and let the handler fire fresh.
        """
        with self._prompt_cache_lock:
            cached = self._prompt_cache.get(fingerprint)
        if cached is None:
            return None
        if cached.action != "choose":
            return (cached.action, cached.payload)
        if cached.chosen_volume_id is None:
            return None
        for i, cand in enumerate(candidates):
            if cand.volume_id is not None and cand.volume_id == cached.chosen_volume_id:
                return ("choose", i)
        return None

    def _store_prompt_resolution(
        self,
        fingerprint: str,
        response: PromptResponse,
        candidates: tuple[Candidate, ...],
    ) -> None:
        """Cache a fresh resolution under its fingerprint."""
        chosen_volume_id: int | None = None
        if response.action == "choose" and isinstance(response.payload, int):
            try:
                chosen_volume_id = candidates[response.payload].volume_id
            except IndexError:
                chosen_volume_id = None
        # Session-level actions (set_prompts / set_policy / abort) are
        # not cached: they apply once, not as a deferred decision.
        if response.action in {"set_prompts", "set_policy", "abort"}:
            return
        entry = _CachedResolution(
            action=response.action,
            payload=response.payload,
            chosen_volume_id=chosen_volume_id,
        )
        with self._prompt_cache_lock:
            self._prompt_cache[fingerprint] = entry

    def _build_config(self) -> ComicboxSettings:
        """
        Build a ComicboxSettings from the session's tagging preferences.

        Layered as ``replace`` over the default settings rather than fed
        through ``get_config(Namespace(...))`` because some of the fields
        we need to set (``enabled``, ``sources``, per-source auth dict)
        live on runtime-only fields the CLI namespace parser ignores.

        Built once in ``__init__``. ``match`` / ``prompts`` are the seed
        values only: every box overlays the live ``OnlineSessionState``
        over them, so a mid-run policy change needs no rebuild here.
        """
        base = self._base_settings
        policy = self._state.snapshot()
        new_lookup = OnlineLookupSettings(
            enabled=True,
            sources=self._sources,
            ids=self._ids,
            match=policy.match,
            prompts=policy.prompts,
            rematch=self._rematch,
            first_wins=self._first_wins,
        )
        new_auth = OnlineAuthSettings(sources=self._build_auth_sources())
        new_online = replace(base.online, lookup=new_lookup, auth=new_auth)
        return replace(base, online=new_online)

    def _build_auth_sources(self) -> dict[str, OnlineSourceCredentials]:
        creds = self._credentials
        return {
            source: OnlineSourceCredentials(
                key=creds.key_for(source), url=creds.url_for(source)
            )
            for source in self._sources
        }

    # -- validation ---------------------------------------------------------

    @staticmethod
    def _validate_sources(sources: tuple[str, ...]) -> None:
        if not sources:
            msg = "OnlineSession requires at least one source"
            raise OnlineConfigurationError(msg)
        unknown = set(sources) - _KNOWN_SOURCES
        if unknown:
            msg = (
                f"Unknown online sources: {sorted(unknown)}. "
                f"Expected a subset of {sorted(_KNOWN_SOURCES)}."
            )
            raise OnlineConfigurationError(msg)

    @staticmethod
    def _validate_ids(sources: tuple[str, ...], ids: Mapping[str, int]) -> None:
        if extra := sorted(set(ids) - set(sources)):
            msg = (
                f"Pinned issue ids for sources not in this session: {extra}. "
                f"Enabled sources: {list(sources)}."
            )
            raise OnlineConfigurationError(msg)

    @staticmethod
    def _validate_credentials(
        sources: tuple[str, ...], creds: OnlineCredentials
    ) -> None:
        missing = [
            f"{source} requires {_REQUIRED_CREDENTIAL[source]}"
            for source in sources
            if not creds.key_for(source)
        ]
        if missing:
            msg = "Missing credentials for enabled online source(s):\n  " + "\n  ".join(
                missing
            )
            raise OnlineConfigurationError(msg)

    def _validate_match(self, match: MatchMode) -> MatchMode:
        if not isinstance(match, MatchMode):  # pyright: ignore[reportUnnecessaryIsInstance]
            msg = f"OnlineSession.match must be a MatchMode enum value; got {match!r}."  # pyright: ignore[reportUnreachable]
            raise OnlineConfigurationError(msg)
        # ASK auto-writes nothing and prompts for every match, so a
        # session with nowhere to send a prompt would write nothing.
        if (
            match is MatchMode.ASK
            and self._prompt_handler is None
            and not self._defer_prompts
        ):
            msg = (
                "OnlineSession.match does not accept MatchMode.ASK without "
                "a way to resolve its prompts: no prompt_handler is set and "
                "defer_prompts is off. Pass a PromptHandler or "
                "defer_prompts=True."
            )
            raise OnlineConfigurationError(msg)
        return match

abort_reason property

Why the session stopped itself, or None if nobody’s lookup aborted.

None after a plain :meth:cancel — that is the caller’s own doing and needs no explanation. Set when a lookup raised OnlineLookupAbortedError, most usefully when the day’s API quota ran out, which stops a run the caller never asked to stop.

cancelled property

Whether cancel() has been called.

defer_prompts property

Whether the session is currently in defer-prompts mode.

match property

Current session match mode (read-only; mutate via set_match()).

set_match accepts MatchMode.ASK only while a prompt handler or deferred prompts can resolve the prompts it raises. A selector answering set_policy: "ask" sets it without that check, so this may report ASK where set_match would refuse.

prompts property

Current session prompt policy.

__enter__()

Enter the context manager, returning this session.

Source code in comicbox/online_session.py
501
502
503
def __enter__(self) -> Self:
    """Enter the context manager, returning this session."""
    return self

__exit__(*_exc_info)

Exit the context manager, releasing pooled connections.

Source code in comicbox/online_session.py
505
506
507
def __exit__(self, *_exc_info: object) -> None:
    """Exit the context manager, releasing pooled connections."""
    self.close()

__init__(*, sources=('metron', 'comicvine'), ids=None, credentials=None, match=MatchMode.AUTO, prompts=Prompts.ASK, prompt_handler=None, on_event=None, rematch=False, first_wins=True, defer_prompts=False, series_batching=True, config=None, client_name=None)

Validate inputs, build per-session state. See class docstring.

Source code in comicbox/online_session.py
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
def __init__(  # noqa: PLR0913
    self,
    *,
    # VerseDB is opt-in: naming it needs a `versedb_key`, so adding it
    # here would fail every existing caller's credential check.
    sources: Iterable[str] = ("metron", "comicvine"),
    ids: Mapping[str, int] | None = None,
    credentials: OnlineCredentials | None = None,
    match: MatchMode = MatchMode.AUTO,
    prompts: Prompts = Prompts.ASK,
    prompt_handler: PromptHandler | None = None,
    on_event: EventHandler | None = None,
    rematch: bool = False,
    first_wins: bool = True,
    defer_prompts: bool = False,
    series_batching: bool = True,
    config: ComicboxSettings | None = None,
    client_name: str | None = None,
) -> None:
    """Validate inputs, build per-session state. See class docstring."""
    # Identify the embedding application in the outgoing User-Agent.
    # Metron's operators cannot otherwise tell a library embedder —
    # which may be running several processes against one token, each
    # with its own rate gate — from the CLI's single-process thread
    # pool. Set before any source builds its client, since clients
    # bake the header in at construction.
    set_user_agent_context("lib", client=client_name)
    # Order is run priority and merge precedence; see the class
    # docstring.
    self._sources = tuple(dict.fromkeys(sources))
    self._validate_sources(self._sources)
    # Pinned per-source issue ids. A source with an id fetches it
    # directly; the rest of the sources search as usual, so one session
    # can mix id retrieval and search and merge both results.
    self._ids: dict[str, int] = dict(ids or {})
    self._validate_ids(self._sources, self._ids)
    self._credentials = credentials or OnlineCredentials()
    self._validate_credentials(self._sources, self._credentials)
    # The prompt resolvers come before the match mode: whether ASK
    # is acceptable depends on having one.
    self._prompt_handler = prompt_handler
    self._defer_prompts = defer_prompts
    self._state = OnlineSessionState(
        match=self._validate_match(match),
        prompts=prompts,
    )
    self._on_event = on_event
    self._rematch = rematch
    self._first_wins = first_wins
    self._series_batching = series_batching
    # Read config files / env exactly once per session. _build_config
    # used to call get_config() per file — wasted disk I/O on big
    # batches plus a behavioral surprise where a config-file edit
    # mid-batch changed settings for the remaining files. A caller
    # that passes its own settings skips the read entirely: they are
    # already the answer this would have gone looking for.
    self._base_settings: ComicboxSettings = (
        config if config is not None else get_config()
    )
    # Nothing in the settings tree varies per file: the mutable
    # policy lives in _state and each box overlays it for itself.
    self._settings: ComicboxSettings = self._build_config()

    # Cancel token. Set when cancel() is called; checked between files
    # in tag_many() and consulted by the wired retry sleep
    # (_retry_sleep_wait), which aborts an in-flight rate-limit wait.
    self._cancel = threading.Event()

    # Prompt-dedup cache. Keyed by fingerprint of (source, normalized
    # series, sorted distinct candidate volume_ids); the stored entry
    # is the PromptResponse the handler returned the first time we
    # saw this fingerprint. For "choose" actions we also record the
    # candidate's volume_id so we can re-map the index when the new
    # prompt's candidate list is ordered differently. Per-session,
    # in-memory only — disk persistence is out of scope for v1.
    self._prompt_cache: dict[str, _CachedResolution] = {}
    self._prompt_cache_lock = threading.Lock()

    # Defer-prompts queue. When ``defer_prompts`` is set, the bridged
    # selector skips the user's PromptHandler and queues the prompt
    # here instead. Codex's flow: drain via ``deferred_prompts()`` at
    # end-of-batch, present in a review UI, then seed resolutions
    # back via ``preload_resolution()`` and re-run the affected files.
    self._deferred: list[DeferredPrompt] = []
    self._deferred_lock = threading.Lock()

    # Series cache (plan §3.10). Keyed by (source_name, series
    # fingerprint); value is the resolved volume_id. Populated by
    # the matcher on each cold-path acceptance; consulted before the
    # cold-path search on subsequent comics of the same series so
    # we make one `search` call per series instead of one per issue.
    # In-memory only per the resolved open question.
    self._series_cache: dict[tuple[str, str], int] = {}
    self._series_cache_lock = threading.Lock()
    # How many comics of each series the current `tag_many` batch
    # holds, by filename fingerprint. Empty for single-file `tag()`,
    # which clusters nothing.
    self._series_cluster_sizes: Counter[str] = Counter()
    # Why a lookup aborted the run, if one did. See `abort_reason`.
    self._abort_reason: str | None = None

cancel()

Stop accepting new files. In-flight lookup runs to completion.

Source code in comicbox/online_session.py
466
467
468
def cancel(self) -> None:
    """Stop accepting new files. In-flight lookup runs to completion."""
    self._cancel.set()

clear_deferred_prompts()

Drop the deferred-prompt queue without resolving them.

Source code in comicbox/online_session.py
551
552
553
554
def clear_deferred_prompts(self) -> None:
    """Drop the deferred-prompt queue without resolving them."""
    with self._deferred_lock:
        self._deferred.clear()

clear_series_cache()

Drop every series resolution from the cache.

Source code in comicbox/online_session.py
606
607
608
609
def clear_series_cache(self) -> None:
    """Drop every series resolution from the cache."""
    with self._series_cache_lock:
        self._series_cache.clear()

close()

Release the pooled connections and cache handles every source holds.

Optional, and not a cancel: the session stays usable afterwards, at the cost of reopening what it needs on its next request. The upstream clients are process-wide per credential set, so closing while another OnlineSession in the same process is mid-run costs that run the same reopen. Acceptable, and the alternative – leaving the sockets and sqlite handles to be finalized – is what emits ResourceWarning.

Comic Vine is the one sharp edge: its rate-limit buckets are closed with the session, so a lookup already holding one can fail outright rather than merely reconnect. Close between files, not under one.

Source code in comicbox/online_session.py
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
def close(self) -> None:
    """
    Release the pooled connections and cache handles every source holds.

    Optional, and not a cancel: the session stays usable afterwards,
    at the cost of reopening what it needs on its next request. The
    upstream clients are process-wide per credential set, so closing
    while another `OnlineSession` in the same process is mid-run
    costs that run the same reopen. Acceptable, and the alternative
    -- leaving the sockets and sqlite handles to be finalized -- is
    what emits `ResourceWarning`.

    Comic Vine is the one sharp edge: its rate-limit buckets are
    closed with the session, so a lookup already holding one can fail
    outright rather than merely reconnect. Close between files, not
    under one.
    """
    from comicbox.formats.comicvine_api.online_source import (
        close_shared_sessions as close_comicvine,
    )
    from comicbox.formats.metron_api.online_source import (
        close_shared_sessions as close_metron,
    )
    from comicbox.formats.versedb_api.online_source import (
        close_shared_sessions as close_versedb,
    )

    close_metron()
    close_comicvine()
    close_versedb()

deferred_prompts()

Snapshot the queued deferred prompts. Codex’s review-UI input.

Source code in comicbox/online_session.py
546
547
548
549
def deferred_prompts(self) -> tuple[DeferredPrompt, ...]:
    """Snapshot the queued deferred prompts. Codex's review-UI input."""
    with self._deferred_lock:
        return tuple(self._deferred)

preload_resolution(fingerprint, *, action, payload=None, chosen_volume_id=None)

Seed the dedup cache so a re-run auto-resolves the fingerprint.

Codex’s defer-mode flow: drain deferred_prompts() after the batch, present them in a review UI, call preload_resolution() for each one the user resolves, then re-tag the affected files (with defer_prompts toggled off if desired). The cache hit fires the same way it does for in-batch dedup. A non-empty cache is enough to install the bridged selector — but with no handler and defer_prompts off, a cache MISS (the re-search produced a different candidate set than the fingerprint was minted from) raises rather than falling back to the interactive CLI prompt.

Source code in comicbox/online_session.py
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
def preload_resolution(
    self,
    fingerprint: str,
    *,
    action: Literal["choose", "skip", "manual"],
    payload: int | str | None = None,
    chosen_volume_id: int | None = None,
) -> None:
    """
    Seed the dedup cache so a re-run auto-resolves the fingerprint.

    Codex's defer-mode flow: drain ``deferred_prompts()`` after the
    batch, present them in a review UI, call ``preload_resolution()``
    for each one the user resolves, then re-tag the affected files
    (with defer_prompts toggled off if desired). The cache hit fires
    the same way it does for in-batch dedup. A non-empty cache is
    enough to install the bridged selector — but with no handler and
    defer_prompts off, a cache MISS (the re-search produced a
    different candidate set than the fingerprint was minted from)
    raises rather than falling back to the interactive CLI prompt.
    """
    entry = _CachedResolution(
        action=action, payload=payload, chosen_volume_id=chosen_volume_id
    )
    with self._prompt_cache_lock:
        self._prompt_cache[fingerprint] = entry

preload_series_resolution(*, source, series_fingerprint, volume_id)

Seed the series cache from outside the session.

Codex’s use case: persist resolved series across runs in its own DB and replay them at session-start to skip the cold-path search entirely on subsequent imports. Same first-writer-wins semantic as in-batch population — if the key is already cached, this is a no-op.

Source code in comicbox/online_session.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def preload_series_resolution(
    self, *, source: str, series_fingerprint: str, volume_id: int
) -> None:
    """
    Seed the series cache from outside the session.

    Codex's use case: persist resolved series across runs in its own
    DB and replay them at session-start to skip the cold-path search
    entirely on subsequent imports. Same first-writer-wins semantic
    as in-batch population — if the key is already cached, this is
    a no-op.
    """
    key = (source, series_fingerprint)
    with self._series_cache_lock:
        self._series_cache.setdefault(key, volume_id)

rate_limit_status()

Snapshot of each enabled source’s current rate-limit budget.

Every entry maps a window name to a JSON-safe limit / remaining / reset_epoch triple, so one renderer handles every source; only the window names differ, because the services meter differently.

Metron carries the live per-account state mokkari>=4 tracks from X-RateLimit-* response headers::

{"burst": {"limit": 20, "remaining": 19, "reset_epoch": ...},
 "sustained": {"limit": 5000, "remaining": 4987, "reset_epoch": ...}}

The sustained (daily) limit varies by Metron OpenCollective donor tier, so it is only discoverable from these headers.

Comic Vine meters per resource, so it reports one window per endpoint pool it has actually used::

{"issues": {"limit": 200, "remaining": 197, "reset_epoch": ...},
 "search": {"limit": 200, "remaining": 199, "reset_epoch": ...}}

Its numbers are read from the rate-limit bucket file rather than from a live client, so they survive across runs and are available before this session issues a request. reset_epoch is when the window’s oldest request ages out and frees the next slot.

VerseDB meters per account per hour, and reports the window its shared client last saw in X-RateLimit-*. It sends no reset time, so reset_epoch is None; the 4,000-a-day cap of its free tier has no header at all::

{"hour": {"limit": 300, "remaining": 287, "reset_epoch": None}}

A source reports {} until it has data: for Metron that means no request has gone out yet in this process (no shared session, or no header seen); for Comic Vine, that no bucket file exists yet or it could not be read; for VerseDB, that no shared client has had a response yet.

Source code in comicbox/online_session.py
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
def rate_limit_status(self) -> dict[str, dict[str, Any]]:
    """
    Snapshot of each enabled source's current rate-limit budget.

    Every entry maps a window name to a JSON-safe
    ``limit`` / ``remaining`` / ``reset_epoch`` triple, so one
    renderer handles every source; only the window names differ,
    because the services meter differently.

    Metron carries the live per-account state mokkari>=4 tracks from
    ``X-RateLimit-*`` response headers::

        {"burst": {"limit": 20, "remaining": 19, "reset_epoch": ...},
         "sustained": {"limit": 5000, "remaining": 4987, "reset_epoch": ...}}

    The sustained (daily) limit varies by Metron OpenCollective donor
    tier, so it is only discoverable from these headers.

    Comic Vine meters per resource, so it reports one window per
    endpoint pool it has actually used::

        {"issues": {"limit": 200, "remaining": 197, "reset_epoch": ...},
         "search": {"limit": 200, "remaining": 199, "reset_epoch": ...}}

    Its numbers are read from the rate-limit bucket file rather than
    from a live client, so they survive across runs and are available
    before this session issues a request. ``reset_epoch`` is when the
    window's oldest request ages out and frees the next slot.

    VerseDB meters per account per hour, and reports the window its
    shared client last saw in ``X-RateLimit-*``. It sends no reset
    time, so ``reset_epoch`` is None; the 4,000-a-day cap of its free
    tier has no header at all::

        {"hour": {"limit": 300, "remaining": 287, "reset_epoch": None}}

    A source reports ``{}`` until it has data: for Metron that means
    no request has gone out yet in this process (no shared session,
    or no header seen); for Comic Vine, that no bucket file exists
    yet or it could not be read; for VerseDB, that no shared client
    has had a response yet.
    """
    statuses: dict[str, dict[str, Any]] = {name: {} for name in self._sources}
    if "metron" in statuses:
        from comicbox.formats.metron_api.online_source import (
            shared_session_rate_limit_status,
        )

        status = shared_session_rate_limit_status(self._credentials.metron_key)
        if status is not None:
            statuses["metron"] = _rate_limit_windows(status)
    if "comicvine" in statuses:
        from comicbox.formats.comicvine_api.online_source import (
            shared_client_rate_limit_status,
        )

        statuses["comicvine"] = shared_client_rate_limit_status(
            self._settings.online
        )
    if "versedb" in statuses:
        from comicbox.formats.versedb_api import online_source as versedb

        statuses["versedb"] = versedb.shared_client_rate_limit_status(
            self._credentials.versedb_key, self._credentials.versedb_url
        )
    return statuses

series_cache_snapshot()

Snapshot the current series cache. Useful for persistence.

Source code in comicbox/online_session.py
601
602
603
604
def series_cache_snapshot(self) -> dict[tuple[str, str], int]:
    """Snapshot the current series cache. Useful for persistence."""
    with self._series_cache_lock:
        return dict(self._series_cache)

set_defer_prompts(*, defer)

Toggle defer-prompts mode for subsequent file lookups.

Turning deferral off leaves the match mode alone, even when it is MatchMode.ASK and no prompt handler is set. The ASK guard in the constructor and set_match is an entry check, not an invariant this toggle re-enforces: a session left in ASK without a resolver prompts for every match, and each lookup reports the missing resolver at prompt time, as for any session without one.

Source code in comicbox/online_session.py
533
534
535
536
537
538
539
540
541
542
543
544
def set_defer_prompts(self, *, defer: bool) -> None:
    """
    Toggle defer-prompts mode for subsequent file lookups.

    Turning deferral off leaves the match mode alone, even when it
    is ``MatchMode.ASK`` and no prompt handler is set. The ASK guard
    in the constructor and ``set_match`` is an entry check, not an
    invariant this toggle re-enforces: a session left in ASK without
    a resolver prompts for every match, and each lookup reports the
    missing resolver at prompt time, as for any session without one.
    """
    self._defer_prompts = defer

set_match(match)

Change the session match mode for subsequent file lookups.

MatchMode.ASK prompts for every match, so it is accepted only while the session has a prompt handler or defers its prompts.

Source code in comicbox/online_session.py
453
454
455
456
457
458
459
460
def set_match(self, match: MatchMode) -> None:
    """
    Change the session match mode for subsequent file lookups.

    ``MatchMode.ASK`` prompts for every match, so it is accepted only
    while the session has a prompt handler or defers its prompts.
    """
    self._state.set_match(self._validate_match(match))

set_prompts(prompts)

Change the session prompt policy for subsequent file lookups.

Source code in comicbox/online_session.py
462
463
464
def set_prompts(self, prompts: Prompts) -> None:
    """Change the session prompt policy for subsequent file lookups."""
    self._state.set_prompts(prompts)

tag(path)

Tag one file synchronously.

Source code in comicbox/online_session.py
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
def tag(self, path: Path) -> OnlineResult:
    """Tag one file synchronously."""
    if self._cancel.is_set():
        return OnlineResult(path=path, cancelled=True)
    try:
        tags, matched = self._run_one(path)
    except OnlineLookupAbortedError as exc:
        # The handler answered "abort", a cancelled retry sleep aborted
        # an in-flight lookup, or the day's API quota ran out. Abort
        # means "abort the entire run", not "skip this file": trip the
        # cancel token so tag_many drains the remaining paths as
        # cancelled.
        #
        # Keep the reason. Every path out of here looks identical to a
        # caller — a stream of cancelled results — but "the user paused
        # it" and "Metron has nothing left today" call for different
        # handling, and the second has to be readable without scraping
        # the log.
        self._abort_reason = str(exc)
        logger.warning(f"online: lookup aborted: {exc}")
        self.cancel()
        return OnlineResult(path=path, cancelled=True)
    except Exception as exc:
        if self._on_event is not None:
            self._on_event(FileError(path=path, error=str(exc)))
        return OnlineResult(path=path, error=exc)
    return OnlineResult(path=path, tags=tags, matched=matched)

tag_many(paths)

Tag many files sequentially. Stops accepting new ones on cancel.

When series_batching is on (the default), paths are reordered upfront by a lightweight filename-derived fingerprint so issues of the same series cluster together. The first issue of each cluster triggers the cold-path search; the remaining issues hit the per-session series cache and skip the search entirely. Order within a cluster is the original input order; the cluster order itself is deterministic (sorted by fingerprint) so re-runs produce identical cache-key sequences.

Counting each cluster up front also lets the source that resolves a series decide to list the whole thing once rather than once per comic (OnlineSource.prefetch_volume) — worth the most here, where the run is sequential and every saved request is saved wall clock too.

Source code in comicbox/online_session.py
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
def tag_many(self, paths: Iterable[Path]) -> Iterator[OnlineResult]:
    """
    Tag many files sequentially. Stops accepting new ones on cancel.

    When ``series_batching`` is on (the default), paths are reordered
    upfront by a lightweight filename-derived fingerprint so issues of
    the same series cluster together. The first issue of each cluster
    triggers the cold-path search; the remaining issues hit the
    per-session series cache and skip the search entirely. Order
    within a cluster is the original input order; the cluster order
    itself is deterministic (sorted by fingerprint) so re-runs
    produce identical cache-key sequences.

    Counting each cluster up front also lets the source that resolves
    a series decide to list the whole thing once rather than once per
    comic (`OnlineSource.prefetch_volume`) — worth the most here,
    where the run is sequential and every saved request is saved wall
    clock too.
    """
    path_list = list(paths)
    if self._series_batching:
        path_list = sorted(path_list, key=filename_series_fingerprint)
        self._series_cluster_sizes = Counter(
            filename_series_fingerprint(path) for path in path_list
        )
    for path in path_list:
        if self._cancel.is_set():
            yield OnlineResult(path=path, cancelled=True)
            continue
        yield self.tag(path)

PromptHandler

Bases: Protocol

Codex’s prompt-resolution callback.

All handlers must implement :meth:request — the single-prompt form used by every code path that ships today. Handlers MAY additionally implement :meth:request_many to opt into the future batched-prompt delivery path (plan §3.4 / step 8): when the engine grows the per-session prompt queue, handlers exposing request_many get the full pending window in one call; handlers without it continue to be invoked one prompt at a time. v1 delivers prompts via request only — see tasks/prepare-for-codex-writing/03-batched-prompt-handler.md for the deferred implementation plan.

Source code in comicbox/online_session.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
@runtime_checkable
class PromptHandler(Protocol):
    """
    Codex's prompt-resolution callback.

    All handlers must implement :meth:`request` — the single-prompt form
    used by every code path that ships today. Handlers MAY additionally
    implement :meth:`request_many` to opt into the future batched-prompt
    delivery path (plan §3.4 / step 8): when the engine grows the
    per-session prompt queue, handlers exposing ``request_many`` get the
    full pending window in one call; handlers without it continue to be
    invoked one prompt at a time. v1 delivers prompts via ``request``
    only — see ``tasks/prepare-for-codex-writing/03-batched-prompt-handler.md``
    for the deferred implementation plan.
    """

    def request(self, prompt: OnlinePrompt) -> PromptResponse:
        """Resolve one prompt; return the chosen action/payload."""
        ...

request(prompt)

Resolve one prompt; return the chosen action/payload.

Source code in comicbox/online_session.py
190
191
192
def request(self, prompt: OnlinePrompt) -> PromptResponse:
    """Resolve one prompt; return the chosen action/payload."""
    ...

PromptResponse dataclass

Codex-side decision for one prompt.

action mirrors :data:SelectorAction; payload is the index for choose, the "<source>:<id>" string for manual, the new :class:MatchMode value (e.g. "auto") for set_policy, the new :class:Prompts value (e.g. "never") for set_prompts, or None otherwise.

Source code in comicbox/online_session.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@dataclass(frozen=True, slots=True)
class PromptResponse:
    """
    Codex-side decision for one prompt.

    ``action`` mirrors :data:`SelectorAction`; ``payload`` is the index for
    ``choose``, the ``"<source>:<id>"`` string for ``manual``, the new
    :class:`MatchMode` value (e.g. ``"auto"``) for ``set_policy``, the new
    :class:`Prompts` value (e.g. ``"never"``) for ``set_prompts``, or
    ``None`` otherwise.
    """

    action: Literal["choose", "skip", "manual", "abort", "set_prompts", "set_policy"]
    payload: int | str | None = None

Prompts

Bases: StrEnum

Whether comicbox is allowed to prompt the user mid-run.

Source code in comicbox/config/online/settings.py
45
46
47
48
49
class Prompts(StrEnum):
    """Whether comicbox is allowed to prompt the user mid-run."""

    ASK = "ask"
    NEVER = "never"

RunEstimate dataclass

The projected cost of a batch online-tag run.

Source code in comicbox/online_estimate.py
145
146
147
148
149
150
151
152
@dataclass(frozen=True, slots=True)
class RunEstimate:
    """The projected cost of a batch online-tag run."""

    requests: int
    """Total API requests the run is expected to make."""
    seconds: float
    """Projected wall-clock duration in seconds."""

requests instance-attribute

Total API requests the run is expected to make.

seconds instance-attribute

Projected wall-clock duration in seconds.

SourceAttribution dataclass

A credit and the link it must carry.

Source code in comicbox/formats/base/online/attribution.py
15
16
17
18
19
20
@dataclass(frozen=True, slots=True)
class SourceAttribution:
    """A credit and the link it must carry."""

    text: str
    url: str

estimate_run(comics, sources, *, effort=Effort.BALANCED.value, merge_all_sources=False)

Project the request count and wall-clock seconds for a batch online-tag run.

comics is how many comics remain to look up and sources the enabled source names in priority order. effort is an :class:~comicbox.config.online.settings.Effort value ("balanced" etc.), resolved for the source it prices. merge_all_sources mirrors first_wins=False: every source is queried per comic and their per-comic costs summed, instead of stopping at the first match.

The projection assumes the effort it is handed. A CLI run can auto-engage a lower Comic Vine effort for a large unattended batch, which this cannot see.

Source code in comicbox/online_estimate.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def estimate_run(
    comics: int,
    sources: Sequence[str],
    *,
    effort: str = Effort.BALANCED.value,
    merge_all_sources: bool = False,
) -> RunEstimate:
    """
    Project the request count and wall-clock seconds for a batch online-tag run.

    ``comics`` is how many comics remain to look up and ``sources`` the
    enabled source names in priority order. ``effort`` is an
    :class:`~comicbox.config.online.settings.Effort` value (``"balanced"``
    etc.), resolved for the source it prices. ``merge_all_sources`` mirrors
    ``first_wins=False``: every source is queried per comic and their
    per-comic costs summed, instead of stopping at the first match.

    The projection assumes the effort it is handed. A CLI run can
    auto-engage a lower Comic Vine effort for a large unattended batch,
    which this cannot see.
    """
    sources = tuple(sources)
    if comics <= 0 or not sources:
        return RunEstimate(requests=0, seconds=0.0)
    per_source = [requests_per_comic(source, effort) for source in sources]
    # Merge sums every source's per-comic cost; first-match-wins bills the
    # costliest single source the run might hit.
    per_comic = sum(per_source) if merge_all_sources else max(per_source)
    requests = comics * per_comic
    # Merge pays every source per comic; first-match-wins isn't done until
    # the binding (slowest) source answers.
    paces = [_seconds_per_comic(source, effort) for source in sources]
    seconds_per_comic = sum(paces) if merge_all_sources else max(paces)
    return RunEstimate(requests=requests, seconds=comics * seconds_per_comic)

source_attribution(name)

Return the credit name’s terms require, or None when they ask for none.

Source code in comicbox/formats/base/online/attribution.py
23
24
25
26
27
28
29
30
31
def source_attribution(name: str) -> SourceAttribution | None:
    """Return the credit ``name``'s terms require, or None when they ask for none."""
    from comicbox.formats import FORMAT_REGISTRATIONS

    for registration in FORMAT_REGISTRATIONS.values():
        info = registration.cli_info
        if info is not None and info.short_name == name and info.attribution:
            return SourceAttribution(text=info.attribution, url=info.website)
    return None