openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Feed Registry & Acquisitions Import System (Epic)

Open ronibhakta1 opened this issue 6 months ago • 8 comments

Feature Request

Feed Registry & Acquisitions Import System (formerly "Trusted Book Providers (TBP) Ingestion Pipeline")

Problem / Opportunity

Open Library currently lacks a standardized mechanism for ingesting and tracking metadata from trusted external book providers such as BWB OPDS, Lenny, and Standard Ebooks.

As Open Library expands partnerships with external providers, we need infrastructure that can:

  • Track trusted provider feeds and ingestion progress.
  • Process provider records incrementally.
  • Associate provider metadata with Open Library editions.
  • Store acquisition-related metadata for downstream indexing and discovery.
  • Enable future integrations with additional feed types (OPDS, ONIX, Standard Ebooks, etc.).

Without this infrastructure, onboarding new trusted providers requires ad-hoc solutions and makes ongoing synchronization difficult to maintain.

Success Criteria

  • Trusted provider feeds can be registered and tracked.
  • Feed ingestion can run incrementally.
  • Provider metadata is persisted against editions.
  • Acquisition records are stored separately for indexing purposes.
  • Solr can react to acquisition-related updates.

Current Status (2026-07-23)

This issue was auto-closed as "completed" on 2026-06-21 when PR #12851 merged and referenced "Closes #12844" — but that PR only covered Subtask 2 of the 4 below. Reopening: this is the right issue to track the integrated end-state, since it already frames the full pipeline (registry → acquisitions → ingestion → Solr surfacing) rather than any one piece of it.

Real state of each piece, as of this update:

  • Feed Registry DB — designed via PR #12846 (tbp_feed_registry table + FeedRegistry class), but that PR is closed, unmerged, and now shows CONFLICTING — needs a fresh PR rebased on current master.
  • Acquisitions DB — table + interface merged via PR #12851, but not yet wired into the live import/acquisition flow (nothing populates or reads it in production yet).
  • BWB OPDS ingestion script — drafted via PR #12852 (open, draft, mergeable), not yet integrated into the actual import flow.
  • Acquisitions in Solr — not started. Current plan is to dynamically fetch acquisitions from the DB at query time and weave them into results as needed, rather than embedding acquisition data directly into the Solr index — avoids ballooning the index, but the query-time join pattern needs its own design pass (see Subtask 4 below, revised).

Open question carried over from original triage, still unresolved: how this relates to #5792 ("Trusted Book Providers", the longer-running epic led by @cdrini) and #12655 ("Epic: BookWorm — Modernize the Import Pipeline", a distinct-but-adjacent effort on the general import queue/DB). Worth a scope conversation before further subtask PRs land, so effort doesn't split across three epics tracking overlapping ground.

Related, not yet reconciled:

  • #5792 — Trusted Book Providers (epic)
  • #10251 — Simplify Trusted Book Providers integration
  • #12655 — Epic: BookWorm — Modernize the Import Pipeline
  • #11264 — Add Solr acquisitions field for BookServer integration

Proposal

Introduce a Trusted Book Provider (TBP) ingestion pipeline consisting of:

  1. A tbp_feed_registry table to track trusted feeds and ingestion progress.
  2. An acquisitions table for provider-specific acquisition metadata.
  3. A cron-based ingestion process that fetches and processes provider feeds.
  4. Solr integration that recognizes acquisition updates and provider metadata.

The initial implementation will focus on:

  • BWB OPDS
  • Internet Archive Labs Lenny

Future providers such as Standard Ebooks and ONIX feeds should be supported through the same framework.

Breakdown

Parent Issue Tracking

  • [x] 1. Create tbp_feed_registry table and seed initial provider entries — PR #12846 (closed, unmerged, conflicting — needs a fresh PR)
  • [x] 2. Create acquisitions table for acquisition metadata — PR #12851 (merged; not yet wired into live flow)
  • [x] 3. Implement Trusted Book Provider ingestion cron — PR #12852 (open, draft; BWB script drafted, not integrated)
  • [ ] 4. Extend solr-updater to process acquisition updates — not started; revised plan is query-time DB fetch, not index-time embedding (see Current Status above)

Subtask 1: Create tbp_feed_registry Table

Current status: Designed in PR #12846, but that PR is closed/unmerged and now conflicting. Needs a fresh PR before this can move forward.

Goal

Track available provider feeds and ingestion progress.

Requirements

  • Create migration for tbp_feed_registry
  • Store:
    • provider name
    • feed type (opds, onix, standardebooks, etc.)
    • feed URL
    • last processed timestamp
    • last fetch date
    • metadata JSON
  • Manually seed:
    • BWB OPDS
    • Lenny

Acceptance Criteria

  • Registry table exists.
  • Feed metadata can be stored.
  • Initial provider records can be added manually.

Subtask 2: Create acquisitions Table

Current status: Merged via PR #12851. Table and interface exist, but nothing in the live import/acquisition flow populates or reads it yet — still needs wiring.

Goal

Store acquisition metadata associated with Open Library editions and works.

Requirements

  • Create migration for acquisitions
  • Store:
    • work key
    • edition key
    • provider
    • acquisition timestamp
    • metadata JSON blob
  • Support future acquisition metadata such as pricing and provider-specific data.
  • Ensure compatibility with work/edition merges through resolve_redirects.

Acceptance Criteria

  • Acquisition records can be inserted and updated.
  • Records remain valid after merges.
  • Metadata blob supports future expansion.

Subtask 3: Implement Trusted Book Provider Ingestion Cron

Current status: BWB OPDS feed importer script drafted in PR #12852 (open, draft, mergeable), not yet integrated into the actual ingestion flow.

Goal

Fetch provider feeds and update Open Library records.

Requirements

  • Daily cron execution.
  • Read providers from tbp_feed_registry.
  • Initial support for:
    • BWB OPDS
    • Lenny
  • For BWB:
    • Fetch all records initially.
    • Track update timestamps for future incremental processing.
  • Query Open Library editions for latest provider identifiers.
  • Update:
    • Edition metadata (when necessary)
    • Acquisition records
  • Persist ingestion state back to registry.

Acceptance Criteria

  • Cron successfully processes BWB feed.
  • Edition records are updated.
  • Acquisition records are upserted.
  • Registry state advances after successful ingestion.

Subtask 4: Extend Solr Updater for Acquisition Support

Current status: Not started. Revised plan (2026-07-23): rather than extending solr-updater to embed acquisition data at index time, dynamically fetch acquisitions from the acquisitions DB table at query time and weave them into results as needed. Avoids ballooning the Solr index, but needs care around query patterns (efficient batch lookup for a page of search results, caching) to avoid trading index bloat for query-time latency.

Goal

Allow acquisition and provider metadata to be surfaced in search/discovery results.

Requirements (revised)

  • Efficient query-time lookup of acquisition records for a set of editions/works returned by a search.
  • Avoid N+1 DB queries per search result page.
  • Surface provider metadata (price, download options, etc.) alongside search results.

Original requirements (index-time approach, superseded above, kept for reference)

  • Extend solr-updater to:
    • Detect TBP-related edition changes.
    • Detect acquisition record changes.
  • Trigger reindexing when:
    • Edition metadata changes.
    • Acquisition metadata changes.
  • Surface provider metadata within indexed records.

Acceptance Criteria

  • Acquisition data is surfaced in search results without materially increasing Solr index size.
  • Provider metadata is available for display/filtering.
  • Existing indexing behavior remains unaffected.
Implementation Details (for maintainers)

Related files

Potential areas of implementation:

  • Database migrations
  • openlibrary/core/
  • openlibrary/plugins/
  • scripts/
  • openlibrary/solr/
  • Cron configuration

Refer to: https://docs.openlibrary.org/developers/backend/endpoints.html

Requirements Checklist

  • [ ] Create tbp_feed_registry table (PR #12846 needs a fresh, unblocked replacement).
  • [ ] Seed BWB and Lenny feed records.
  • [x] Create acquisitions table (PR #12851, merged).
  • [ ] Wire acquisitions table into the live import/acquisition flow.
  • [ ] Implement feed ingestion cron (PR #12852 drafts the BWB piece; not yet integrated).
  • [ ] Update editions with provider metadata.
  • [ ] Upsert acquisition records.
  • [ ] Design + implement query-time acquisition lookup for search results (revised Subtask 4).
  • [ ] Add relevant documentation.

Stakeholders

  • @mekarpeles
  • @cdrini
  • @ronibhakta1

Instructions for Contributors

  • Before creating a new branch or pushing changes to a PR, please first run the repository update commands to ensure your repository is up to date, as the pre-commit bot may add commits to your PRs upstream.

ronibhakta1 avatar Jun 03 '26 03:06 ronibhakta1

Thank you @ronibhakta1 for submitting this issue!

⚠️ Contributors, this issue will be ready to work on once:

  • [ ] Triage — maintainers will add Priority: * and Lead: @* to replace Needs: Triage and Needs: Lead
  • [ ] Needs: Investigation — significant overlap exists with recently merged work (PR #12793) and the existing Trusted Book Providers epic (#5792); scope must be reconciled before implementation begins
  • [ ] Needs: Breakdown — subtask tracking references #1–#4 as placeholder numbers rather than filed GitHub issues; subtasks should be opened as separate issues once scope is confirmed

Context

  • openlibrary/book_providers.py already contains an Acquisition dataclass (line 69) and acquisition feed support via from_opds_json (line 116). Any proposed acquisitions DB table should be assessed against this existing abstraction.
  • openlibrary/plugins/importapi/import_opds.py is an existing OPDS parser used by the import API — relevant to the feed ingestion design.
  • scripts/import_standard_ebooks.py implements Standard Ebooks ingestion using openlibrary.core.imports.Batch. The issue lists Standard Ebooks as a future provider, but it already has an importer and is tracked as complete in #5792.
  • PR #12793 (merged 2026-05-27) added scripts/bwb_opds_imports.py, a daily incremental BWB OPDS 2.0 importer. This directly overlaps with Subtask #3 (ingestion cron for BWB). The issue does not reference this.
  • Issue #5792 ("Trusted Book Providers") is the existing epic covering this initiative, led by @cdrini. This issue should be assessed against that tracking issue before proceeding independently.

Issue Assessment

Open questions

  • How does this proposal relate to the existing Trusted Book Providers epic (#5792) and PR #12793? Is this intended to supersede, extend, or sit alongside that work?
  • The proposed acquisitions table — how does it differ from the existing Acquisition class in book_providers.py, which already models OPDS acquisition data? Is a DB table needed, or does the existing in-memory representation suffice?
  • Is "Internet Archive Labs Lenny" a public service or internal IA infrastructure? If the latter, any sub-task depending on it would be Needs: Staff / Admin.
  • The stakeholders section lists @drini — is this a typo for @cdrini?

Action items

  • [ ] Clarify how this issue relates to #5792 and PR #12793; confirm what scope is still open
  • [ ] File Subtasks #1–#4 as separate GitHub issues (with links replacing the #1–#4 placeholders) once scope is confirmed by a lead
  • [ ] Confirm whether Lenny is publicly accessible or requires internal access

Full triage checklist (maintainers / Pam)
  • [x] Triage — labels applied: added Needs: Investigation; Needs: Triage, Needs: Lead, Needs: Breakdown retained pending staff review
  • [x] Problem / opportunity — problem stated (no standardized provider ingestion mechanism); audience is maintainers and future contributors
  • [ ] Scope — overlaps significantly with PR #12793 (BWB) and #5792 (TBP epic); not yet reconciled
  • [ ] Justification — impact framed as operational ("ad-hoc solutions"), no measurable scale or urgency stated
  • [ ] Success & testing criteria — acceptance criteria present per subtask but lack testable observable conditions (e.g. row counts, idempotency guarantees, rollback behavior)
  • [x] Proposal & breakdown — table schemas and task structure described; subtasks need to be filed as separate issues
  • [ ] If bug: environment & repro steps — N/A (feature request)
  • [ ] Risks, concerns, open questions — Lenny access not clarified; Solr schema changes for acquisition fields not specified; resolve_redirects compatibility mentioned but not fully analyzed
  • [x] Pam context — book_providers.py, import_opds.py, import_standard_ebooks.py, PR #12793, issue #5792 reviewed
  • [ ] References — no schema diagrams or examples from the existing codebase pattern (schema.sql) provided

[!NOTE] This comment was automatically generated by Pam, Open Library's Project AI Manager, on behalf of @mekarpeles. Pam is designed to provide status visibility, perform basic project management functions and relevant codebase research, and provide actionable feedback so contributors aren't left waiting.

mekarpeles avatar Jun 03 '26 04:06 mekarpeles

Progress update (Ada, on behalf of Mek): working an integration prototype that brings the open pieces here together into one tested branch before splitting back into atomic PRs.

Branch: 12844/feed-registry-acquisitions (off master, fully additive so far, +607/-0).

Reconciliation: #12852 supersedes #12846 (same feed-registry pieces + a BWB rewrite + a synthetic OPDS test fixture) — treating it as the reference rather than duplicating. Kept the already-merged #12793 BWB script as the working baseline rather than adopting #12852's full rewrite.

Landed so far, all test-covered:

  • tbp_feed_registry table + FeedRegistry interface (register/advance/find/all) — 7 tests.
  • BWB OPDS ingestion idempotency proven via a synthetic feed fixture + DB-backed tests — repeated runs do not duplicate import_item rows.
  • First live writer for the acquisitions table (merged via #12851 but previously unwired) — idempotent upsert keyed on (local_id, provider_name).
  • 57 tests green across all four related modules, in both collection orders.

Still open before this splits into real PRs: a feed-registration HTTP endpoint, resolving how acquisitions attach once BWB creates import records ahead of the edition existing, and whether the registry cursor replaces the script's current file-based state. Will keep this issue posted as those land.

openlibrary-bot avatar Jul 24 '26 23:07 openlibrary-bot

Integration prototype opened as draft #13206 (will be split into atomic PRs before landing).

Working & unit-tested (SQLite level): tbp_feed_registry+FeedRegistry, BWB OPDS ingestion idempotency, first live writer of the acquisitions table, POST /api/import/feeds/register, FeedRegistry cursor as source of truth, in-run acquisition attach for already-resolved editions, and a synthetic mockservices OPDS feed.

Not yet: no live end-to-end run (feed → manage-imports → real edition → acquisition); the post-import hook for newly-created editions is written but not yet wired into the import pipeline; Solr surfacing remains docs-only.

Next: generalizing the BWB script into a reusable OPDS 2.0 adapter (openlibrary/catalog/opds2.py) so onboarding a new OPDS feed is a registry row, not a script; then the operator surface (/admin/imports/registry, harvest trigger, multi-feed cron) and the dedicated staging service.

openlibrary-bot avatar Jul 27 '26 16:07 openlibrary-bot

Feed Registry & Acquisitions Import System

Status: in-flight (prototype) Sources: code synthesis on branch 12844/feed-registry-acquisitions / draft PR #13206 (openlibrary/core/tbp.py, openlibrary/core/acquisitions.py, openlibrary/core/schema.sql, scripts/bwb_opds_imports.py, scripts/manage-imports.py, openlibrary/plugins/importapi/code.py, openlibrary/plugins/importapi/import_opds.py, openlibrary/catalog/add_book/, docker/mockservices/main.py, compose.yaml, compose.override.yaml) Last ingested: 2026-07-27 Epic: internetarchive/openlibrary#12844 (Feed Registry & Acquisitions Import System); related #12655 (BookWorm), #5792 (Trusted Book Providers), #11264 (Solr acquisitions)

⚠️ Design in flight. This system is actively being built. Most of it is planned; a tested prototype layer exists on branch 12844/feed-registry-acquisitions (draft PR #13206), verified at the SQLite/unit level only — no live end-to-end loop has run yet. Everything below is annotated built vs planned/in-flight; treat the planned parts as design intent, not shipped behavior.

This is the shared-context architecture doc for the epic. It describes the target ("end-state") system, then two flow diagrams: the import ecosystem (how partner feeds become catalog records + acquisitions) and the catalog system (how any import record becomes a Work/Edition in Infogami + Solr). It complements [[trusted-book-providers]], which covers where acquisition data lives today and the migration off Infogami edition objects.


End-state overview & goals

Open Library is a catalog of every book: each unique work (the parent) has one or more editions (children), and an edition may carry zero or more acquisitions — OPDS-style options to buy (a price, currency, link), borrow, or read it. Today, onboarding a new trusted partner feed (BWB OPDS, Lenny, Standard Ebooks, Cita Press, …) means writing a bespoke ingestion script per source. The goal of this epic is to make onboarding a feed "add a registry row," not "write and deploy a script," and to give acquisitions a real home so they can be searched and surfaced.

The target system has five moving parts:

  1. Feed Registry (tbp_feed_registry, main OL psql) — the source of truth for which partner feeds OL ingests, each row holding the feed URL, an incremental cursor (last_updated), the connector type, and an open-ended data blob (trust level, polling cadence, record caps, cover-import flag). Feeds are added two ways: partners self-enlist via POST /api/import/feeds/register (recorded status="pending", awaiting maintainer promotion — mirroring the account-linking policy for Lenny lending instances), or maintainers manage them through an /admin/imports/registry CRUD surface.

  2. Registry-driven adapters — instead of one script per source, the registry parameterizes a small set of connector types: opds2 (the near-term focus — a generic OPDS 2.0 adapter at openlibrary/catalog/opds2.py), plus planned jsonl_url, marc_bulk, and api. Per-source quirks (e.g. BWB's specific fields) become centrally-maintained special-cases rather than forked scripts. The existing bespoke BWB importer is the reference implementation that will collapse into the generic opds2 adapter.

  3. Staging (BookWorm, #12655) — a dedicated bookworm FastAPI container with its own isolated staging-db psql, so bulk feed harvesting never contends with production OL psql. It owns the harvest cron(s) and holds a raw staged_record buffer plus its own import_batch/import_item tables. This is the "separate DB, FastAPI service, real-time OPDS bot" idea from the BookWorm epic.

  4. manage-imports (dual-source) — the existing continuous batch-import processor evolves to drain both the legacy main-schema import_batch/import_item and the BookWorm staging-db's import tables, promoting staged records into the real catalog. ImportBot (running on ol-home0 in prod, the home container in dev) drives it, hitting the existing import API endpoints.

  5. Acquisitions + Solr — acquisitions are edition-scoped facts (price, format, access, URL) that currently live incorrectly on Infogami edition objects (the providers list). They move to the acquisitions table (main OL, one row per (edition, provider), keyed on (local_id, provider_name) so work/edition merges never conflict). Acquisitions are surfaced in search via query-time DB fetch (join at query time for a page of results), not by embedding them in the Solr index — avoiding index bloat. This lets patrons eventually search by price / availability ("what books are for sale?", "what's available through trusted providers?") and feeds ebook_access deduction. Open question (unresolved): whether well-defined implicit providers like IA's ~6M ocaids should be materialized as rows or stay derived — see [[trusted-book-providers]].

Build status at a glance

Piece State Notes
tbp_feed_registry + FeedRegistry (register/advance/find/all/from_request) Built core/tbp.py; lives in main OL psql schema; unit/SQLite-tested only
acquisitions table + Acquisition interface Built core/acquisitions.py; merged via #12851; stays in main OL
First live acquisitions writer (build_acquisition_data / upsert_acquisition) Built in the BWB script; idempotent upsert on (local_id, provider_name)
POST /api/import/feeds/register Built auth-gated (can_write→403); records submitter + status="pending"
FeedRegistry cursor = source of truth for BWB incremental state Built resolve_cutoff/advance_cursor; file-state is fallback only
Edition resolution option (a): in-run attach for ISBNs that already resolve Built resolve_edition_ids + stage_acquisitions (existing editions only)
mockservices synthetic BWB OPDS 2.0 feed Built docker/mockservices/main.py → /services/bwb/opds
Generic opds2 adapter (openlibrary/catalog/opds2.py); BWB collapses into it Planned today the BWB importer is bespoke; importapi/import_opds.py is a separate OPDS 1.x XML parser
link_acquisition_for_edition post-import hook wiring Planned wiring the function EXISTS but is called by nothing except its own test — not wired into manage-imports/add_book
/admin/imports/registry view + feed CRUD + manual harvest + per-feed lock + multi-feed cron Planned operator surface
bookworm container + staging-db + staged_record buffer + its own import tables Planned Option B of #12655; owns harvest cron; runs on dev too
manage-imports dual-source drain (legacy + bookworm staging-db) Planned today it drains only the legacy main-schema import tables
Solr surfacing of acquisitions (query-time DB fetch) Planned (docs-only) no code yet
Live end-to-end loop (feed → manage-imports → real edition → acquisition) Not yet run core remaining validation target

Diagram 1 — Import ecosystem

⚠️ Design in flight; built vs planned as annotated. Solid green = built & unit-tested; dashed amber = planned / in-flight. "Built" here means unit/SQLite-tested on the prototype branch, not live in production.

flowchart TB
    subgraph LEGEND["Legend"]
        direction LR
        LB["Built (unit-tested)"]:::built
        LP["Planned / in-flight"]:::planned
    end

    %% ---- Provider feeds ----
    subgraph SRC["Provider feeds (external)"]
        BWBFEED["BWB OPDS 2.0 feed"]:::built
        OTHERFEEDS["Lenny / Standard Ebooks /<br/>Cita Press / ..."]:::planned
    end
    MOCK["mockservices container<br/>synthetic BWB OPDS<br/>/services/bwb/opds"]:::built

    %% ---- Feed registration ----
    POST["POST /api/import/feeds/register<br/>auth-gated, status=pending"]:::built
    ADMIN["/admin/imports/registry<br/>feed CRUD + manual harvest trigger"]:::planned
    REGTBL[("tbp_feed_registry<br/>url + cursor + connector cfg<br/>(main OL psql)")]:::built
    POST --> REGTBL
    ADMIN -.-> REGTBL

    %% ---- Adapters ----
    subgraph ADP["Registry-driven adapters (by connector type)"]
        BWBSCRIPT["scripts/bwb_opds_imports.py<br/>bespoke BWB importer (opds2)"]:::built
        OPDS2["catalog/opds2.py<br/>generic OPDS 2.0 adapter"]:::planned
        OTHERCONN["jsonl_url / marc_bulk / api<br/>connectors"]:::planned
    end
    REGTBL -- "drives; cursor = source of truth" --> BWBSCRIPT
    REGTBL -.-> OPDS2
    REGTBL -.-> OTHERCONN
    BWBFEED --> BWBSCRIPT
    MOCK --> BWBSCRIPT
    OTHERFEEDS -.-> OPDS2
    BWBSCRIPT -. "collapses into" .-> OPDS2

    %% ---- Staging / batch DBs ----
    LEGACYIMP[("import_batch / import_item<br/>(legacy, main OL psql)")]:::built
    BWBSCRIPT -- "stage olbook records" --> LEGACYIMP

    subgraph BW["bookworm service (planned, #12655)"]
        BWCRON["harvest cron(s)<br/>multi-feed runner + per-feed lock"]:::planned
        STAGEDB[("staging-db (isolated psql)<br/>staged_record buffer +<br/>import_batch / import_item")]:::planned
    end
    REGTBL -. "read feeds" .-> BWCRON
    BWCRON -.-> STAGEDB
    OPDS2 -.-> STAGEDB

    %% ---- Promotion into catalog ----
    MI["scripts/manage-imports.py<br/>(dual-source: legacy + bookworm)"]:::built
    LEGACYIMP -- "drains today" --> MI
    STAGEDB -. "drains (planned)" .-> MI
    IB["ImportBot on ol-home0<br/>(home container cron)"]:::built
    MI --> IB
    EP["Import API<br/>POST /api/import, /api/import/ia"]:::built
    IB --> EP
    CAT["Catalog System<br/>add_book.load()  — see Diagram 2"]:::built
    EP --> CAT
    INFOGAMI[("Infogami DB<br/>Works + Editions")]:::built
    CAT --> INFOGAMI

    %% ---- Acquisitions ----
    ACQ[("acquisitions table (main OL)<br/>work_id, edition_id, provider, data")]:::built
    BWBSCRIPT -- "in-run upsert<br/>(ISBN already resolves)" --> ACQ
    HOOK["link_acquisition_for_edition<br/>post-import hook"]:::planned
    CAT -. "planned wiring" .-> HOOK
    HOOK -.-> ACQ

    %% ---- Solr ----
    SOLR["Solr<br/>ebook_access; acquisitions<br/>surfaced via query-time DB fetch"]:::builtplanned
    INFOGAMI --> SOLR
    ACQ -. "query-time join (planned)" .-> SOLR

    classDef built fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#111;
    classDef planned fill:#fff8e1,stroke:#f9a825,stroke-width:2px,stroke-dasharray:5 5,color:#111;
    classDef builtplanned fill:#e3f2fd,stroke:#1565c0,stroke-width:2px,color:#111;

Notes: Solr itself is built (blue = exists today, computing ebook_access from the edition), but acquisition surfacing from the new table is the planned query-time-fetch part. manage-imports and ImportBot exist today (built) draining the legacy tables; the dual-source second drain from the bookworm staging-db is the planned addition.


Diagram 2 — Catalog System (add_book.load())

⚠️ Design in flight, but this diagram documents EXISTING catalog behavior — the pipeline every import path already terminates in today (openlibrary/catalog/add_book/). It is the "under the hood" of the Catalog System node in Diagram 1. The only in-flight element is the dashed acquisitions hook, which is not yet wired in.

flowchart TB
    IN["Import record (JSON)<br/>title + source_records<br/>(+ISBNs, authors, ...)"]
    IN --> LOAD["add_book.load(rec)"]

    LOAD --> ISPROMISE{"is_promise_item?"}
    ISPROMISE -- "no" --> VR["validate_record()<br/>required fields"]
    ISPROMISE -- "yes (skip)" --> NORM
    VR --> NORM["normalize_import_record()<br/>ISBN norm, author dedup,<br/>HTML unescape"]

    NORM --> POOL["build_pool()<br/>candidate editions by<br/>ISBN / LCCN / OCLC / source_records"]
    POOL --> EMPTY{"pool empty?"}
    EMPTY -- "yes" --> LD["load_data() — create path"]
    EMPTY -- "no" --> MATCH["find_match()<br/>threshold_match scoring"]
    MATCH --> HASMATCH{"edition match?"}
    HASMATCH -- "no" --> LD
    HASMATCH -- "yes" --> UPD["update_edition_with_rec_data()<br/>update_work_with_rec_data()<br/>merge new fields into existing"]

    subgraph CREATE["load_data() — new / overwrite"]
        direction TB
        R2E["import_record_to_edition()<br/>build edition dict"]
        AUTH["load_author_import_records()<br/>find_author / find_entity<br/>→ match or create Author"]
        WORKQ{"find_matching_work()?"}
        NEWWORK["new_work() — create Work"]
        MWORK["attach to matched Work<br/>(merge subjects/covers)"]
        R2E --> AUTH --> WORKQ
        WORKQ -- "no" --> NEWWORK
        WORKQ -- "yes" --> MWORK
    end
    LD --> R2E

    UPD --> SAVE["site.save_many(edits)"]
    NEWWORK --> SAVE
    MWORK --> SAVE

    SAVE --> INFO[("Infogami DB<br/>/works/OL...W + /books/OL...M")]
    INFO -. "if cover_url" .-> COVER["add_cover() → covers service"]
    INFO -. "if ocaid" .-> IAMETA["update_ia_metadata_for_ol_edition()<br/>writes back to archive.org item"]

    INFO --> EDITLOG["Infogami edit log"]
    EDITLOG --> SU["solr-updater<br/>updater/edition.py + updater/work.py"]
    SU --> SOLR["Solr index<br/>ebook_access, ebook_provider,<br/>has_fulltext, providers[]"]

    ACQHOOK["link_acquisition_for_edition<br/>(planned wiring — not called today)"]:::planned
    INFO -. "planned" .-> ACQHOOK

    classDef planned fill:#fff8e1,stroke:#f9a825,stroke-width:2px,stroke-dasharray:5 5,color:#111;

Key behaviors this captures (all existing): every import path — direct /api/import, IA bulk MARC, batch queue — funnels into add_book.load(); promise items skip validate_record; matching is ISBN/LCCN/OCLC-pool + threshold_match; a matched edition is updated in place while an unmatched record creates Edition + (matched-or-new) Work + (matched-or-new) Author; everything is persisted via one site.save_many(edits) into Infogami, which the solr-updater reflects into Solr. ebook_access / providers[] are computed from the Infogami edition at index/fetch time today (see [[trusted-book-providers]]).


Key files

File Role State
openlibrary/core/tbp.py FeedRegistry interface + cursor built
openlibrary/core/acquisitions.py Acquisition DB interface (upsert on (local_id, provider_name)) built
openlibrary/core/schema.sql (~L135, ~L152) acquisitions + tbp_feed_registry DDL (main schema) built
scripts/bwb_opds_imports.py BWB OPDS importer; first acquisitions writer; link_acquisition_for_edition hook built (hook unwired)
openlibrary/plugins/importapi/code.py (feed_register_api, ~L513) POST /api/import/feeds/register built
openlibrary/plugins/importapi/import_opds.py OPDS 1.x XML parser (distinct from the 2.0 JSON path) existing
scripts/manage-imports.py batch-import drainer / promoter (do_import→import API) built (single-source)
openlibrary/catalog/add_book/__init__.py (load, load_data) catalog record creation existing
openlibrary/catalog/add_book/load_book.py author resolution + import_record_to_edition existing
docker/mockservices/main.py (~L443) synthetic BWB OPDS feed endpoint built
compose.override.yaml (home, mockservices, db) dev services; ImportBot host; no bookworm/staging-db yet mixed

openlibrary-bot avatar Jul 27 '26 20:07 openlibrary-bot

Adding a related sub-issue to this epic: #12138 (Solr Bulk Indexing for BWB & Lenny OPDS price data) — folded in here per Mek's direction rather than tracked as its own separate top-level epic.

mekarpeles avatar Jul 28 '26 20:07 mekarpeles

v1 prod setup: DB tables + feed registrations

Recording the manual prod steps for the Feed Registry & Acquisitions v1 (#13241). These are applied by hand on prod for v1; openlibrary/core/schema.sql already carries the same DDL so fresh dev/prod instances get them automatically (no migration script needed).

1. Tables (run on prod)

feed_registry is new in this PR. acquisitions came in via #12851 — only create it if not already present (\dt acquisitions).

CREATE TABLE feed_registry (
    id serial primary key,
    provider_name text not null,
    feed_type text not null default 'opds',
    url text not null,
    last_updated timestamp without time zone default null,
    data jsonb not null default '{}'::jsonb,
    created timestamp without time zone default (current_timestamp at time zone 'utc'),
    updated timestamp without time zone default (current_timestamp at time zone 'utc'),
    UNIQUE (provider_name, url)
);
CREATE INDEX feed_registry_provider_name ON feed_registry (provider_name);

-- acquisitions (#12851) — only if not already present
CREATE TABLE acquisitions (
    id serial primary key,
    work_id integer not null,
    edition_id integer not null,
    provider_name text not null,
    local_id text not null,
    data jsonb not null,
    created timestamp without time zone default (current_timestamp at time zone 'utc'),
    updated timestamp without time zone default (current_timestamp at time zone 'utc'),
    UNIQUE (local_id, provider_name)
);
CREATE INDEX acquisitions_work_id_idx ON acquisitions (work_id);
CREATE INDEX acquisitions_edition_id_idx ON acquisitions (edition_id);
CREATE INDEX acquisitions_updated_idx ON acquisitions (updated);

2. Feed registrations (run on prod)

The data blob holds the connector config (id_strategy, cursor_style). For modified_since feeds (Gutenberg) the harvester overwrites the modified_since query param each run from the cursor, so it is not stored in the URL; seed last_updated instead to bound the first backfill.

INSERT INTO feed_registry (provider_name, url, last_updated, data) VALUES
('lenny', 'https://lennyforlibraries.org/v1/api/opds',
 NULL, '{"id_strategy":"self_link","cursor_style":"client","status":"pending"}'::jsonb),
('project_gutenberg', 'https://opds-test.pglaf.org/opds/search?sort=fil',
 '2026-07-20', '{"id_strategy":"gutenberg","cursor_style":"modified_since","status":"pending"}'::jsonb),
('betterworldbooks', 'https://www.betterworldbooks.com/opds',
 NULL, '{"id_strategy":"isbn","cursor_style":"client","status":"pending"}'::jsonb);

Still required for a working prod v1

  • Set BOOKWORM_INTERVAL_SECONDS=3600 (default is 300, testing).
  • Real bookworm service deploy config (the compose service is dev-only) + authenticated ImportBot path.
  • Rebase #13241 onto master.

openlibrary-bot avatar Aug 21 '26 14:08 openlibrary-bot

Re-import of changed acquisitions, and Amazon as an internal feed source

Framing and proposal by @mekarpeles; written up by an agent on his behalf, with the code references verified against master (7d9d2cb). This is a proposal with open questions, not a settled design.


The problem

The Feed Registry exists so that provider data — notably BWB price changes — reaches Open Library. Today it cannot, and the block is earlier than most people assume.

The catalog side already handles updates correctly:

  • add_book.load() pops acquisitions off the record and, on success, calls _save_acquisitions()
  • _save_acquisitions() calls Acquisition.upsert(), a real ON CONFLICT (local_id, provider_name) DO UPDATE SET ... data = EXCLUDED.data — so a changed price does overwrite the stored one
  • _load() returns success: True on the created and matched paths, so a re-import of an unchanged edition still reaches the upsert

The update is lost one step earlier, in Batch.dedupe_items:

SELECT ia_id FROM import_item WHERE ia_id IN $ia_ids

That query is unscoped to batch, to status, and to time — the whole import_item table, forever. Any ia_id ever seen (including rows that ended failed) is silently dropped by add_items and never re-queued. The harvester's _submit() goes through exactly this path.

Why that protection exists and is load-bearing (Mek): it stops firehose sources — Amazon price lookups, daily archive.org imports — re-queuing the same record every month when only acquisition data changed and the bibliographic metadata did not. When Amazon metadata was previously wired to queue into import_item, OL's DB performance fell over and the site could not keep up. There is also a hard disk-space cost to unbounded growth.

So: the same mechanism that protects prod is now the thing blocking the Feed Registry's core purpose.


Three code facts worth correcting before anyone designs against this

  1. ia_id is not globally unique in the schema. The DB constraint is UNIQUE (batch_id, ia_id) (schema.py#L101). Global uniqueness is application policy enforced only by dedupe_items. Changing the dedupe rule — e.g. per-source, or time-windowed — needs no migration, just a change to that one function. This makes options (b) and (d) below considerably cheaper than they look.

  2. Completed rows already drop their payload. ImportItem.set_status sets data=None for every non-failed terminal status. The growth cost of completed rows is therefore row count and index size, not blob size. Worth re-measuring before the disk-space argument drives the decision.

  3. In-place status reset is already a supported pattern. ImportItem.bulk_mark_pending does UPDATE import_item SET status='pending' WHERE status='staged' AND ia_id IN (...). Option (b) is not a new concept in this codebase; it is an extension of one already in production.

One more, relevant to option (d): on master the harvester submits into a single permanent {provider}-opds batch, so UNIQUE(batch_id, ia_id) would block a re-submit even without dedupe_items. #13565 changes the batch name to date-scoped ({provider}-opds-%Y-%m-%d), which removes the DB-level block — leaving dedupe_items as the only remaining barrier.


Options on the table

Presented with tradeoffs, not as a recommendation.

Option Pro Con
(a) Move completed records to a separate import-history DB; live import_item stays small. The catalog decides whether anything actually changed (as long as acquisitions and missing fields still get picked up). Keeps the hot table small and fast; preserves full per-import history. Matches the import_item_history design already sketched in #12655. Most infrastructure. Pushes "did anything change?" into the catalog, which is the busiest, riskiest place to add work. Needs an archival job.
(b) Re-use the existing row: set status back to pending, replace data. Most efficient and practical; table does not grow at all; precedent exists (bulk_mark_pending). Muddies per-import history — one row, many imports, one import_time. Side effects: what happens to a row currently processing? To ol_key/error from the prior run? Re-pending a failed row could re-trigger a known-bad import on a loop.
(c) New id / new field per import (a fresh row for every re-observation). Cleanest history; no mutation of past records. Works directly against the goal — grows the table exactly the way that caused the original performance problem.
(d) Date in the import id, for feed-driven channels only (e.g. bwb:978...:2026-09-06), on the reasoning that if the Feed Registry surfaced a record at all, it genuinely needs re-processing. Scoped to feeds; leaves the firehose protection intact for everything else. With #13565's date-scoped batches, no schema change needed. Still one row per re-observation, i.e. (c)'s growth curve narrowed to feed sources. Changes the meaning of ia_id, which is parsed as {source}:{identifier} in several places (find_staged_or_pending, import_first_staged, single_import). Would need an audit of every consumer.

Pressure release: much of this eases once BookWorm has its own FastAPI service and its own database (#12655), where ia_id stops being the blocking constraint and the queue is no longer contending with prod. But that is not landing this quarter, and an interim answer is still needed for BWB prices.


Brainstorm: Amazon as a data source + an internal feed type

⚠️ Explicitly a brainstorm from Mek, not advice, and not costed. Recorded here so it can be argued with.

1. Amazon lands in a date-indexed key-value store. Updating a record (say ISBN 1234567890) is an upsert — an insert or a dict-merge — rather than a new row. Today Amazon products go to memcache with a one-week TTL (affiliate_server.py#L438-L441) and are separately staged into import_item as status=staged (L458). Note memcache exposes no per-entry age, so any freshness rule (below) requires a durable store with a fetch timestamp — memcache alone cannot express it. Mek's own flagged risk: the I/O cost of this store is real and unquantified.

2. Amazon becomes a feed of type: internal in the Feed Registry. Instead of staging ad hoc on every page view, a daily internal feed processes whatever records accumulated that day and clears the queue. Amazon moves from ad hoc to a daily cadence, and rides the same registry/cursor/status machinery as BWB, Gutenberg and Lenny.

This also fixes a smaller thing: _save_acquisitions drops any acquisition whose provider_name is not in feed_registry (add_book/init.py#L1054-L1056). Amazon cannot write acquisitions today for exactly that reason. Registering it as an internal feed is the mechanism that unblocks Amazon prices as first-class acquisitions.

3. Future read path (freshness-gated).

  • Cached price < ~3 days old → serve the acquisition price directly, no Amazon call.
  • Otherwise → serve the cached price and queue an Amazon call that repopulates the Amazon table, which in turn imports the acquisition.
  • The production DB acts as the cache, so Amazon calls are not wasted.

4. Important nuance: when no price exists in the DB at all, the Amazon response must be usable immediately from cache — before it has become an acquisition item in the catalog. The read path cannot be "acquisitions table only".

5. Harvest rate. BookWorm's harvester controls its own cadence — cursor-based modified_since, per-feed status gating, and a flush size — which may mean the original overwhelm problem is avoidable this time. Do not over-read this: there is currently no safe per-run record cap. The only knob that looks like one, max_pages, is documented in harvest.py as a testing cap only, because truncating a crawl still advances the cursor past pages it never fetched. A genuine throttle would have to be built.


Open questions for a decision

  1. Which option for the interim? (a) history DB, (b) in-place reuse, (c) new rows, (d) date-in-id for feeds — or a narrower fifth: scope dedupe_items by source, so feed-registry sources dedupe within a time window and everything else keeps today's behaviour. That is a single-function change with no migration.
  2. If (b): what are the exact reset semantics? Which prior statuses are eligible for re-pending (found/created/modified yes; failed? processing?), and what happens to ol_key, error, import_time?
  3. What is the actual measured cost? Row count and index size of import_item today, and the delta a daily BWB re-observation would add. The earlier performance incident is the justification for the current design; the numbers should be re-checked before it constrains the 2026 design.
  4. Should the catalog short-circuit acquisition-only changes? i.e. a cheap path where load() sees an identical bibliographic record and does Acquisition.upsert without re-running match/merge. That would make cheap re-queuing safe and reduce the pressure on whichever dedupe option is chosen.
  5. Does the internal feed type belong in feed_registry, with url null and a connector instead of an OPDS endpoint — or is it a sibling concept? This determines whether _save_acquisitions's registry guard covers Amazon for free.
  6. Where does the Amazon KV store live — prod openlibrary DB, the new openlibrary_imports DB (#12655), or BookWorm's own? Mek's I/O concern points away from prod.
  7. Is the 3-day freshness window right, and is it uniform, or per-provider?

Related: #12655 (BookWorm epic — separate DB removes the ia_id constraint entirely), #13565 (harvest cron, date-scoped batches), #12138 (BWB/Lenny price in Solr), #11318 and #13277 (affiliate-server load/outage history — direct evidence for the "don't overwhelm prod" constraint), #13316 (979-prefix ISBNs Amazon cannot look up at all).

openlibrary-bot avatar Sep 06 '26 20:09 openlibrary-bot

Marking this epic as done; acquisitions in solr still remain

mekarpeles avatar Oct 06 '26 05:10 mekarpeles