Metadata-Version: 2.4
Name: rust_scholar_transformer
Version: 0.3.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
License-File: LICENSE
Summary: Real-time multi-source retrieval core engine (Rust) with a Python binding — arXiv/news/blog/YouTube/web fan-out, normalize, dedup, RRF rank fusion.
Keywords: retrieval,search,rag,arxiv,news,rss,multi-source,rank-fusion,dedup
Author: rust_scholar_transformer contributors
License: Apache-2.0
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/arabangoo/rust_scholar_transformer

# rust_scholar_transformer

> **A real-time multi-source retrieval core engine, written in Rust.**
>
> It fetches arXiv, Semantic Scholar, news, blogs, YouTube, and the web concurrently, then runs
> **normalize -> deduplicate -> rank fusion -> caching**, and exposes a search core that an LLM or Python uses with a one-line import.

This document is the **complete developer manual** for the library. It covers the design philosophy, the public API, per-source behavior and limitations, Python usage, how to add a new source, and the build and test workflow.

**Key references**

1. Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (Cormack et al., SIGIR 2009) - https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
2. LSHBloom: Memory-efficient, Extreme-scale Document Deduplication (2024) - https://arxiv.org/abs/2411.04257
3. Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE, 2022) - https://arxiv.org/abs/2212.10496

---

## Table of Contents

1. [Key Features](#1-key-features)
2. [Quick Start](#2-quick-start)
3. [Installation and Cargo Features](#3-installation-and-cargo-features)
4. [Architecture](#4-architecture)
5. [Common Data Model Reference](#5-common-data-model-reference)
6. [Public API Reference](#6-public-api-reference)
7. [Per-Source Behavior and Maturity](#7-per-source-behavior-and-maturity)
8. [Deduplication and Rank Fusion](#8-deduplication-and-rank-fusion)
9. [Cache and Rate Limiting](#9-cache-and-rate-limiting)
10. [Python Bindings (PyO3)](#10-python-bindings-pyo3)
11. [Embedding into a Service Pipeline](#11-embedding-into-a-service-pipeline)
12. [Adding a New Source Adapter](#12-adding-a-new-source-adapter)
13. [Build, Feature Combinations, and Testing](#13-build-feature-combinations-and-testing)
14. [Directory Layout](#14-directory-layout)
15. [License](#15-license)
16. [Changelog](#16-changelog)

---

## 1. Key Features

In a RAG / research agent, external knowledge retrieval (the latest papers, news, and web) directly determines answer quality, yet the Rust ecosystem lacks **a single core that federates, normalizes, deduplicates, and re-ranks multiple sources asynchronously**. This library is not a plain fetch; it aims to be **a collection, normalization, and ranking engine that prepares material an LLM can trust and cite**.

| Principle | What it means |
|---|---|
| **Multi-source federation** | One query fetches arXiv, Semantic Scholar, news, blogs, YouTube, and web concurrently (tokio fan-out) and normalizes them into a single [`Document`](#5-common-data-model-reference). |
| **Deterministic local processing** | Live API results are non-deterministic, but **the local processing (normalization, deduplication, rank fusion) is deterministic**: the same per-source result lists always yield the same order and dedup outcome, regardless of which source answered first. |
| **Plugin-extensible** | A new source needs only one trait, [`Source`](#61-the-source-trait). The core stays untouched. |
| **Resilient** | If one source fails or times out, the rest of the results survive and the failure is reported as a warning in the [`SearchReport`](#63-searchreport-and-error-types). |
| **Model-free, zero-FFI by default** | The default build is **pure Rust with no neural-network or LLM dependency**. Semantic understanding, summarization, and re-ranking are the caller's (LLM's) job. |

### Why multi-source federation

A single fetch is network-bound, so the language difference is small. Where Rust makes a difference is **large concurrent fan-out plus result post-processing** (normalization, deduplication, rank fusion, caching): these are CPU and concurrency work, where GIL-free Rust wins on throughput and memory.

```text
one LLM's fetch(url) = fetch a single page
this engine = fetch many sources at once -> normalize -> deduplicate -> rank fusion -> prepare citable material
```

There is one boundary between the core and the caller: **can it be done deterministically without a model (core), or does it require understanding and generating meaning (caller).** What to search, summarizing results, generating answers, and semantic re-ranking are the caller's job (LLM/Python).

---

## 2. Quick Start

### Rust library

```rust
use rust_scholar_transformer::{ArxivSource, Engine, GoogleNewsSource, SearchQuery};

#[tokio::main]
async fn main() {
    let mut engine = Engine::new();
    engine.register(Box::new(ArxivSource::new()));       // no key needed
    engine.register(Box::new(GoogleNewsSource::new()));  // no key needed

    let report = engine.search(SearchQuery::from_text("agentic loop engineering", 20)).await;
    for d in &report.docs {
        println!("[{:?}] {} ({})", d.source, d.title, d.url);
    }
    for w in &report.warnings {
        eprintln!("warning from {:?}: {}", w.source, w.message);
    }
}
```

### Python

Results are returned as a JSON string (serialization stability first).

```python
import json
from rust_scholar_transformer import Retriever

r = Retriever(sources=["arxiv", "news"])          # works with zero keys
report = json.loads(r.search("agentic loop engineering", limit=20))
for d in report["docs"]:
    print(d["source"], d["title"], d["url"])
for w in report["warnings"]:                      # includes sources that returned nothing
    print("warning:", w["source"], w["message"])
```

Write focused queries. Terms are combined with `AND`, so a long natural-language sentence can legitimately
return nothing. Use two or three keywords, or quote a phrase, and narrow by arXiv category when it helps:

```python
r = Retriever(sources=["arxiv"], arxiv_categories=["cs.CL", "eess.AS"])
report = json.loads(r.search('"speaker diarization" whisper', limit=10))
```

Date windows, sort order, citation counts, and caching are optional arguments:

```python
r = Retriever(sources=["arxiv", "s2"], cache="memory")
report = json.loads(r.search('"speaker diarization"', limit=10,
                             sort="citations", from_date="2024-01-01", to_date="2025-12-31"))
for d in report["docs"]:
    print(d["sources"], d["extra"].get("citationCount"), d["title"])
```

---

## 3. Installation and Cargo Features

`Cargo.toml`:

```toml
[dependencies]
rust_scholar_transformer = "0.3"
```

### Feature list

| Feature | Enables | Notes |
|---|---|---|
| (default) | all source adapters + L1 in-memory cache + rate limiting | pure Rust, zero FFI |
| **`cache-disk`** | L2 disk cache | `redb` (pure Rust, expiry checks) |
| **`python`** | PyO3 cdylib bindings | `pyo3` (abi3, Python 3.9+) |

```toml
# default = []  # free, keyless core + all adapters, zero FFI
rust_scholar_transformer = { version = "0.3", features = ["cache-disk"] }
```

> The default build requires no external `.so/.dll` and no subprocess. The L1 cache (`moka`) and rate limiter are pure Rust and included by default; only the disk cache (`redb`) and Python bindings (`pyo3`) are explicit features. The published Python wheel is built with both `python` and `cache-disk`. Transport security uses rustls (avoiding a system OpenSSL dependency).

---

## 4. Architecture

```text
SearchQuery -> Engine (fan-out + per-source concurrency cap + rate limit) -> [Source adapters run concurrently]
    -> normalize (single Document) -> results reordered by registration order
    -> identity grouping + weighted RRF fusion -> MinHash-LSH near-duplicate
    -> recency/date filter -> cache (successful reports only) -> SearchReport (docs + warnings)
```

The heart of it is the **single Document layer** and the **Source trait abstraction**. Each adapter normalizes a source's own response into a [`Document`](#5-common-data-model-reference), and the engine performs fusion, deduplication, and filtering without knowing the source kind.

- **Collection**: an adapter is registered in the [`Engine`](#62-engine) as a [`Source`](#61-the-source-trait) implementation. If a per-source rate policy exists, a limiter is attached automatically at registration.
- **Fusion**: per-source result order is preserved and fused with [RRF](#8-deduplication-and-rank-fusion); when the same document appears in multiple sources, its rank contributions add up.
- **Deduplication**: identity-based (identifier) merging plus MinHash-LSH near-duplicate merging.
- **Filter and cache**: after a recency/date filter, top results are loaded into the cache and returned.

Because it calls live external APIs, the results themselves are non-deterministic. Determinism applies only to the local processing (normalization, deduplication, rank fusion).

---

## 5. Common Data Model Reference

The `model` module. Every type implements `serde::{Serialize, Deserialize}`.

```rust
pub struct Document {
    pub identity:     DocIdentity,           // deduplication key
    pub source:       SourceKind,            // Arxiv | News | Blog | Youtube | Web | Scholar
    pub title:        String,
    pub url:          String,
    pub authors:      Vec<Author>,
    pub published_at: Option<DateTime<Utc>>,
    pub fetched_at:   DateTime<Utc>,
    pub summary:      Option<String>,
    pub content:      Option<String>,
    pub language:     Option<String>,
    pub tags:         Vec<String>,
    pub sources:      Vec<SourceKind>,       // sources that provided the same document (merge tracking)
    pub score:        Score,
    pub extra:        HashMap<String, serde_json::Value>, // per-source raw data preserved
}

pub struct DocIdentity {
    pub doi:           Option<String>,
    pub arxiv_id:      Option<String>,       // normalized: 2301.00001v2 -> 2301.00001
    pub canonical_url: Option<String>,       // canonical URL after removing tracking parameters
    pub title_hash:    u64,                  // fallback when no identifier (FNV-1a)
}

pub struct Author { pub name: String, pub id: Option<String> }

/// Serialized as the enum name by serde. `Scholar` is Semantic Scholar (added in 0.3.0).
pub enum SourceKind { Arxiv, News, Blog, Youtube, Web, Scholar }

pub struct Score {
    pub fused:     f64,   // (weighted) RRF fusion result: the primary sort axis
    pub freshness: f64,   // freshness: the first tie-breaker
    pub authority: f64,   // per-source-kind prior, reported only (not used for ordering)
    pub relevance: f64,   // reserved; not populated by the core (always 0.0)
}
```

What the date and metadata fields mean, per source:

| Field | arXiv | Semantic Scholar | RSS / news |
| --- | --- | --- | --- |
| `published_at` | first submission (`<published>`) | `publicationDate` (midnight UTC; the venue's date, which may differ from the arXiv date) | the item's `pubDate` |
| `fetched_at` | when this engine received the response | same | same |
| `extra` | `primaryCategory`, `updated` (last revision) | `citationCount`, `influentialCitationCount`, `year`, `venue`, `s2PaperId`, `openAccessPdf` | none |
| `tags` | all arXiv categories | `fieldsOfStudy` | none |

A missing `citationCount` means the source did not report one; `0` means the paper has no counted citations. Citation counts are an attention signal from one index, not a measure of correctness.

Query type:

```rust
pub struct SearchQuery {
    pub text:            String,
    pub sources:         Vec<SourceKind>,   // empty = all registered sources
    pub limit:           usize,             // unified top-K (not the per-source fetch count)
    pub language:        Option<String>,
    pub recency:         Option<Recency>,   // Day | Week | Month | Year
    pub from_date:       Option<DateTime<Utc>>,
    pub to_date:         Option<DateTime<Utc>>,
    pub sort:            SortOrder,         // Recent (default) | Relevance | Citations
    pub include_content: bool,              // not implemented: a Notice warning says so
    pub expansions:      Vec<String>,       // not implemented: a Notice warning says so
}

// helpers: SearchQuery::from_text(text, limit) .with_sources(vec![..]) .with_sort(SortOrder::Citations)
//          .with_recency(Recency::Month) .with_dates(Some(from), Some(to))
```

Query semantics:

- `sort` orders results **inside each source**. The final list is always in fused (RRF) order, so `sort="citations"` with several sources gives "the most cited candidates from Semantic Scholar, fused with the others", not a citation-ordered list. For a strictly citation-ordered list, query Semantic Scholar alone.
- `recency` and `from_date`/`to_date` combine into one window; the narrower lower bound wins. `recency` counts back from now in exact durations (`Month` is 31 days), not whole calendar days.
- `to_date` given as a date covers that whole day (a document published at 15:00 on the `to_date` is kept).
- Documents with no publication date are **kept** by the date filter, because "unknown" is not "outside the window".
- `from_date` after `to_date` returns no documents and an `error` warning without calling any source.

---

## 6. Public API Reference

### 6.1 The `Source` Trait

Implemented by every source adapter. A new source implements only this and registers with the engine.

```rust
#[async_trait::async_trait]
pub trait Source: Send + Sync {
    fn kind(&self) -> SourceKind;
    async fn search(&self, query: &SearchQuery) -> Result<Vec<Document>, FetchError>;
    // what the engine calls; the default wraps `search` with no notes
    async fn search_with_notes(&self, query: &SearchQuery) -> Result<SourceOutput, FetchError>;
    fn rate_policy(&self) -> RatePolicy;   // default implementation provided
}

pub struct SourceOutput { pub docs: Vec<Document>, pub notes: Vec<SourceNote> }
pub struct SourceNote   { pub kind: WarningKind, pub message: String }   // SourceNote::notice(..), ::partial(..)

pub struct RatePolicy { pub min_interval_ms: u64, pub max_concurrency: usize, pub daily_quota: Option<u32> }
```

Override `search_with_notes` when a source has something to say besides its documents: a partial failure inside the source, or a requested option it could only approximate. `daily_quota` is not enforced by the engine yet.

### 6.2 `Engine`

```rust
let mut engine = Engine::new()
    .with_timeout(Duration::from_secs(10))      // per-source budget (see below)
    .with_near_dup_threshold(0.7)               // MinHash-LSH merge threshold
    .with_source_weight(SourceKind::News, 0.5)  // optional: weighted RRF (default weight 1.0)
    .with_cache(Box::new(cache));               // optional: result cache
engine.register(Box::new(source));              // concurrency cap + rate limiter attached from rate_policy()
engine.note_unconfigured(SourceKind::Youtube, "needs a key");   // reported as a warning on every search

let report: SearchReport = engine.search(query).await;
```

`search` runs in this order: check cache, concurrent fan-out, reorder results by registration order, identity grouping and weighted RRF fusion, near-duplicate merge, date filter, top `limit`, cache (only if no source failed).

- **The timeout is the whole budget for one source**: waiting for its concurrency slot and minimum interval, retries and their sleeps, the request, and reading the body. A source that exceeds it becomes a `timeout` warning.
- **Per-source concurrency is enforced.** `RatePolicy.max_concurrency` caps how many requests one registered source has in flight, also across concurrent `search` calls on the same engine. The minimum interval applies per registered source instance; two engines (or two processes, or two machines) calling arXiv do not coordinate. Keeping the arXiv total under its terms is the caller's job.

### 6.3 `SearchReport` and Error Types

```rust
pub struct SearchReport { pub docs: Vec<Document>, pub warnings: Vec<ConnectorWarning> }
pub struct ConnectorWarning { pub source: SourceKind, pub message: String, pub kind: WarningKind }

#[derive(thiserror::Error)]
pub enum FetchError { Http(String), Parse(String), RateLimit(String), InvalidQuery(String) }
```

A single source failing does not fail the whole search: the failure is reported in `warnings` alongside the successful results. Branch on `kind` (serialized in lowercase), not on the message text:

| `kind` | Meaning | Counts as a failure (not cached) |
| --- | --- | --- |
| `empty` | the source answered with 0 documents | no |
| `timeout` | the source used up its budget | yes |
| `ratelimited` | HTTP 429 and the retry budget could not cover the next wait | yes |
| `partial` | part of the source failed (one of several RSS feeds); its other results are present | yes |
| `unconfigured` | the source was requested but has no key or feed list, so it never ran | no |
| `notice` | not a failure: a requested option was approximated or is not implemented | no |
| `error` | anything else (network, HTTP status, parse, invalid query) | yes |

Reports written by 0.2.x have no `kind`; it deserializes as `error`.

### 6.4 Adapter Constructors

```rust
ArxivSource::new()                          // live search API (primary). .with_categories(vec!["cs.CL".into()])
                                            //   .with_retry(n, delay) .with_retry_budget(d) .with_user_agent(..)
ArxivOaiSource::new()                       // OAI-PMH recent-window harvest (secondary).
                                            //   .with_from_days(n) .with_set("cs") .with_max_pages(n)
SemanticScholarSource::new()                // academic graph (0.3.0). .with_api_key(k) .with_fields_of_study(v)
                                            //   .with_min_citations(n) .with_retry_policy(p) .with_user_agent(..)
RssSource::new(vec![FeedSource::new("name", "url").with_reliability(0.95)])
GoogleNewsSource::new()                     // .with_locale_tag("ko-KR") or .with_locale("ko", "KR", "KR:ko", "ko")
                                            //   .with_user_agent(..)
YoutubeSource::new(api_key)                 // requires a Data API v3 key
WebSource::new(Box::new(BraveProvider::new(api_key)))   // requires a Brave key
RetryPolicy::new(max_retries, base_delay, budget)        // shared 429 policy (Retry-After seconds or HTTP date)
```

The default User-Agent of every adapter is `rust_scholar_transformer/<crate version> (+repository URL)`. Put a contact address in it with `with_user_agent` when you run a service.

### 6.5 Cache and Rate Limiting

```rust
Cache (trait): async fn get(&str) -> Option<SearchReport>; async fn put(String, SearchReport);
MemoryCache::new(ttl, max_capacity)              // L1, default
DiskCache::open(path, ttl)                       // L2, feature = "cache-disk"
MinIntervalLimiter::from_millis(ms)              // per-source minimum interval (used automatically by the engine)
```

---

## 7. Per-Source Behavior and Maturity

| Source | Type / key | Status |
|---|---|---|
| arXiv (primary) | `ArxivSource` / no key | live search API over the whole archive. Phrase-aware `AND` query builder, optional `cat:` narrowing, server-side `submittedDate` window, `sortBy=submittedDate` or `relevance`, HTTP status pre-check + budgeted 429 retry |
| Semantic Scholar | `SemanticScholarSource` / key optional | academic graph with citation counts. `sort="recent"` and `"citations"` use the bulk search (`publicationDate:desc`, `citationCount:desc`, up to 1,000 per call); `"relevance"` uses the relevance search (up to 100 per call). Date window, fields of study, and minimum citations go to the server. One request per search: no pagination yet, and a `notice` warning says so when `limit` is larger than one page |
| arXiv (secondary) | `ArxivOaiSource` / no key | OAI-PMH harvest of the last N days + in-memory `AND` filter, optional `resumptionToken` paging. For sweeping a recent window by category, and as a fallback. Heavy: about 3.6 MB / 1300 records per page |
| Blogs/RSS | `RssSource` / no key | fetch of subscribed feeds (at most 8 at a time) + keyword filter + per-feed reliability. A failing feed becomes a `partial` warning |
| News | `GoogleNewsSource` / no key | Google News RSS search (public RSS, not an API). Date window sent as `after:`/`before:` operators; locale via `with_locale_tag` |
| YouTube | `YoutubeSource` / **key required** | Data API v3 metadata. Does not handle captions (below) |
| Web | `WebSource` + `BraveProvider` / **key required** | provider abstraction. Brave by default |

Verification and limitation notes:

- **Free, keyless core.** arXiv, Semantic Scholar, Google News RSS, and blog RSS work without an API key. Semantic Scholar without a key shares one rate limit with every unauthenticated caller, so 429s are common; a free key gives you your own limit. YouTube and web need a key. Requesting a source without its key or feed list produces an `unconfigured` warning instead of an empty, silent result. Since no LLM is called, no LLM key is needed either.
- **Sources do not share one query language.** arXiv combines the terms with `AND` and keeps quoted phrases. Semantic Scholar's bulk search treats `|` as OR and quotes as phrases; its relevance search ranks by its own relevance model. The blog RSS filter keeps an item when **any** query word appears in its title or summary (case-insensitive substring, an OR). Google News applies its own search. The same query string therefore selects different things per source.
- **arXiv has no citation counts.** `sort="citations"` falls back to relevance order for arXiv and adds a `notice` warning saying so.
- **Retries stay inside the budget.** On HTTP 429 the adapters honour `Retry-After` (seconds or an HTTP date) or back off exponentially, but only while the total sleep fits the retry budget (arXiv default 7 s, Semantic Scholar 6 s; the Python binding sets 70% of `timeout_secs`). If the next wait would not fit, the adapter does not shorten it and retry early; it returns a `ratelimited` error at once. The budget covers sleeps only, so a slow network can still hit the source timeout.
- **Response bodies are capped** at 8 MB (32 MB for one OAI page), counted while receiving rather than trusted from `Content-Length`.
- **The two arXiv paths answer different questions.** `ArxivSource` searches the entire archive and is what you want for "find papers about X". `ArxivOaiSource` cannot do that by construction: OAI-PMH (Open Archives Initiative Protocol for Metadata Harvesting) is a date-based harvest, so anything outside the recent window is unreachable no matter how the query is written. Reach for it when you want to sweep everything a category published in the last N days, or when the live API is unavailable. Note also that OAI `from` filters on the metadata **datestamp**, not the submission date, so an old paper whose metadata was touched will appear in a recent harvest.
- **The OAI path is heavy, so it follows one page by default.** A single `ListRecords` page is roughly 3.6 MB and 1300 records; following three pages measured about 8.5 seconds end to end, which sits against the engine's 10-second per-source timeout. Raise `max_pages` only together with the timeout (`Engine::with_timeout`, or `timeout_secs=` from Python), and expect a source that exceeds it to be reported as a timeout warning rather than silently truncated.
- **Query terms are combined with `AND`.** Quoted spans are kept as phrase searches. This favours precision, which means a long sentence pasted verbatim can legitimately return nothing. When a source returns nothing it says so in `warnings`, so an empty result is never silent.
- **YouTube captions are not handled.** `captions.download` requires the video owner's permission, and unofficial extraction violates the terms of service. Only metadata (title, channel, description, publish date, URL) is handled.
- **The web provider is replaceable.** The search supply chain changes often and is mostly paid, so it sits behind the `WebProvider` trait. Scraping-based providers carry legal risk, so they are kept separate from self-indexed or legal-API providers and used explicitly.
- **Semantic re-ranking is outside the core.** Cross-encoders and the like require an external model and cross the model-free boundary, so the caller (LLM/Python) handles it.

---

## 8. Deduplication and Rank Fusion

The `dedup` and `fusion` modules.

Deduplication is two stages.

1. **Identity grouping (deterministic):** every document contributes all the keys it has: its DOI, its arXiv ID, and its canonical URL (a title hash only when it has none of these). Two documents that share any key are the same document, and grouping follows the keys transitively, so a record with only a DOI and a record with only an arXiv ID end up together when a third record carries both, **in any input order**. Normalization: DOIs drop `https://doi.org/` and `doi:` prefixes and compare case-insensitively; an arXiv DataCite DOI (`10.48550/arXiv.<id>`) is the same identity as that arXiv ID; arXiv IDs drop `arXiv:` and the version suffix (old-style IDs such as `math.GT/0309136v1` included). URLs keep the case of their path and query (`/ABC` and `/abc` are different documents); only tracking parameters and a trailing slash are removed. The group's first document is the representative; empty fields are filled from the others, contributing sources accumulate in `sources`, and `extra` keeps the first value of each key.
2. **MinHash-LSH near-duplicate (conservative):** catch near-dups without shared identifiers (a syndicated news item, an unidentified copy) using MinHash signatures of title+summary shingles (64 hashes, 16 bands). Banding only proposes candidates. A document merges into an earlier representative only when its signature similarity to **that representative** is at least the threshold (`with_near_dup_threshold`, default 0.7) and their strong identifiers do not conflict: two different arXiv IDs, or two different non-arXiv DOIs, are never merged however similar the text. There is no chaining through intermediates. A document with an arXiv ID and one with only a journal DOI can merge, which is how a preprint meets its published version.

Rank fusion does not add raw scores (scores from heterogeneous sources have incomparable scales and meanings). It fuses ranks with **RRF (Reciprocal Rank Fusion)**, optionally weighted per source kind.

```text
fused(d) = Σ_lists  weight_list / (k + best_rank_in_list(d) + 1)      (k = 60, rank from 0)
```

- **One contribution per list.** A document repeated inside one result list counts once, at its best rank. Different lists add up.
- **Weights** come from `Engine::with_source_weight` (Python `source_weights=`), default 1.0. A weight of 0 keeps the source's documents in the results but adds nothing to their score; to drop a source entirely, do not register it. Negative or non-finite weights count as 0; a non-positive or non-finite `k` falls back to 60.
- **Order independence.** Lists are fused in registration order, whichever source answered first, and the final tie-breakers are freshness (today 1.0, 3 days 0.8, 7 days 0.6, 30 days 0.3, older 0.1), then publication date, then the identity key.
- Weighted RRF is a lever, not a default improvement. A 2026 per-query analysis of hybrid retrieval ("The Fusion Tax", arXiv 2610.30612) found that fusion ranks relevant documents below the better single retriever on a sizeable share of queries. Measure on your own snapshot before changing weights.
- `Score.authority` is a fixed prior per source kind (arXiv 0.90, Semantic Scholar 0.88, blog 0.85, news 0.80, web 0.55, YouTube 0.45; a per-feed reliability overrides it). It is reported, not used for ordering, and being on arXiv is not a peer-review signal.

---

## 9. Cache and Rate Limiting

Cache (optional, `Engine::with_cache`):

| Level | Implementation | Character |
|---|---|---|
| L1 in-memory | `MemoryCache` (moka, TTL + capacity cap) | returns instantly with no API call on repeated identical queries |
| L2 disk | `DiskCache` (redb, `cache-disk` feature, expiry checks) | persists across process restarts |

Cache key = a policy version tag + query text (trimmed, case preserved) + sorted source kinds + limit + sort + recency + date bounds + language + `include_content` + expansions + source weights. API keys are never part of the key. Source configuration such as arXiv categories or the RSS feed list is fixed per engine, so use one engine (or one `Retriever`) per configuration rather than sharing a cache across them.

Cache policy: a report is cached only when no source failed (`timeout`, `ratelimited`, `partial`, `error`). A temporary 429 is therefore not frozen for the whole TTL; the next call tries again. Reports with only `empty`, `unconfigured`, or `notice` warnings are cached. Two identical searches running at the same moment both go to the network (no request coalescing yet).

Rate limiting: each registered source gets a semaphore of `rate_policy().max_concurrency` and, if it has a minimum interval, a `MinIntervalLimiter` (arXiv live 3 s, arXiv OAI 0.5 s, Semantic Scholar 1 s). Both are taken inside the source's timeout. Each source is independent, so they do not block one another during fan-out.

---

## 10. Python Bindings (PyO3)

### Installation

```bash
# From PyPI: no Rust toolchain needed, grab the abi3 wheel
pip install rust_scholar_transformer

# From source (latest main): requires a Rust toolchain + maturin on the install machine
pip install maturin
maturin develop --release
```

### API

```python
import json
from rust_scholar_transformer import Retriever

# sources: "arxiv" | "arxiv_oai" | "s2" | "news" | "blog" | "youtube" | "web"
#          (default ["arxiv","news"]; an unknown name raises ValueError)
r = Retriever(
    sources=["arxiv", "s2", "news", "blog", "youtube", "web"],
    rss_feeds=["https://aws.amazon.com/blogs/machine-learning/feed/"],
    youtube_api_key="...",      # optional
    brave_api_key="...",        # optional
    arxiv_categories=["cs.CL"], # optional, narrows the live arXiv search
    arxiv_oai_set="cs",         # optional, only used by the "arxiv_oai" source
    arxiv_oai_days=7,           # optional, harvest window for "arxiv_oai"
    arxiv_oai_max_pages=1,      # optional, resumptionToken pages to follow
    timeout_secs=10,            # optional, per-source budget; retry sleeps get 70% of it
    s2_api_key=None,            # optional, Semantic Scholar key (x-api-key)
    s2_fields_of_study=["Computer Science"],  # optional
    s2_min_citations=None,      # optional
    user_agent=None,            # optional, put a contact address here for services
    news_locale="ko-KR",        # optional, Google News locale (default en-US)
    cache="memory",             # optional: "memory" | "disk" | None (default)
    cache_ttl_secs=3600,        # optional
    cache_path=None,            # required when cache="disk"
    source_weights={"news": 0.5},  # optional, weighted RRF (default 1.0 each)
)

# returns a JSON string; the 0.2.x call shape search(query, limit) still works
report = json.loads(r.search(
    "multi-agent RAG",
    limit=20,                   # 1 to 1000, otherwise ValueError
    sort="relevance",           # "recent" (default) | "relevance" | "citations"
    from_date="2026-01-01",     # "YYYY-MM-DD" or RFC 3339, inclusive
    to_date=None,
    recency=None,               # "day" | "week" | "month" | "year"
))
```

Sync-first design: the work is completed on an internal tokio runtime and exposed like an ordinary function (avoiding asyncio/Jupyter environment differences). **The GIL is released while a search runs**, so other Python threads (including an HTTP server in the same process) keep running, and several threads can share one `Retriever`. Requests to the same registered source still queue behind its concurrency cap. Inside `asyncio`, call it through `loop.run_in_executor` (or `asyncio.to_thread`) so the event loop is not blocked. An awaitable variant and cancellation of an in-flight search are future work.

Invalid input raises `ValueError` up front: an unknown source name (in `sources` or `source_weights`), `sort`, `recency`, or `cache` value, a date that is neither `YYYY-MM-DD` nor RFC 3339, `from_date` after `to_date`, `limit` outside 1 to 1000, or `cache="disk"` without `cache_path`.

### Build and publish

Built as an abi3 wheel (a single wheel for Python 3.9+). All-platform wheel builds and PyPI publishing are done by `.github/workflows/release.yml` (`PyO3/maturin-action`) on a `v*` tag push (Trusted Publishing, no API token needed).

---

## 11. Embedding into a Service Pipeline

### 11.1 Python LLM pipeline: as a search core

```python
import json
from rust_scholar_transformer import Retriever

retriever = Retriever(sources=["arxiv", "news"])

def answer(question: str, llm) -> str:
    docs = json.loads(retriever.search(question, limit=12))["docs"]
    context = "\n\n".join(f"[{i+1}] {d['title']}\n{d.get('summary','')}\n{d['url']}"
                          for i, d in enumerate(docs))
    return llm.generate(question, context=context)   # understanding and answering is the caller's LLM
```

### 11.2 Embed into a Rust service

```rust
let mut engine = Engine::new();
engine.register(Box::new(ArxivSource::new()));
engine.register(Box::new(GoogleNewsSource::new()));
let report = engine.search(SearchQuery::from_text(&q, 20)).await;
// serialize report.docs directly as the response, or pass it as downstream LLM context
```

### 11.3 Key injection

Do not hardcode API keys; inject them at runtime. In Rust via the constructor (`YoutubeSource::new(env_key)`), in Python via the `Retriever(...)` arguments. Read them from environment variables or a secret manager and pass them in.

---

## 12. Adding a New Source Adapter

Implement only the [`Source`](#61-the-source-trait) trait and it registers without touching the core.

```rust
use rust_scholar_transformer::{Document, FetchError, RatePolicy, SearchQuery, Source, SourceKind};

pub struct MySource { /* client, base_url, ... */ }

#[async_trait::async_trait]
impl Source for MySource {
    fn kind(&self) -> SourceKind { SourceKind::Web }

    async fn search(&self, query: &SearchQuery) -> Result<Vec<Document>, FetchError> {
        // 1) fetch  2) parse  3) normalize into Document (fill canonical_url, title_hash, published_at)
        Ok(vec![])
    }

    fn rate_policy(&self) -> RatePolicy {
        RatePolicy { min_interval_ms: 0, max_concurrency: 2, daily_quota: None }
    }
}

// engine.register(Box::new(MySource { .. }));
```

To add a web search provider, implement the [`WebProvider`](#64-adapter-constructors) trait and plug it into `WebSource`; it shares the `Web` source kind while swapping only the provider.

---

## 13. Build, Feature Combinations, and Testing

```bash
# Default: free, keyless core + all adapters, zero FFI
cargo build

# Disk cache / Python bindings
cargo build --features cache-disk
cargo build --features python

# Test / lint
cargo test
cargo clippy --all-targets

# Live smoke test against the real services (excluded from the default run)
cargo test --test live_smoke -- --ignored --nocapture
```

Integration tests mock HTTP responses with wiremock and verify deterministically, so the default run has no live API dependency. `tests/contract_test.rs` holds the 0.3.0 regressions: an RSS feed failing next to a healthy one is reported as `partial`; `/ABC` and `/abc` stay two documents and an item repeated in one feed is not scored three times; a 30-second `Retry-After` is not slept through a 2-second budget; a 9 MB body is rejected; the arXiv date clause and sort reach the server and the citation fallback is reported; the Semantic Scholar bulk and relevance endpoints receive sort, window, minimum citations, fields, and key; and arXiv plus Semantic Scholar views of one paper merge into one document that carries the citation count. Unit tests cover identity grouping in every input order, DOI and arXiv normalization, near-duplicate identifier conflicts and non-chaining, one-contribution-per-list fusion, list-order independence, zero weights, cache-on-success, unconfigured and notice warnings, the date filter, and the timeout covering the wait for a source.

**Run the live smoke test before a release.** Mocks verify that the parser handles a response; they cannot verify that the adapter builds a query the real service accepts. That gap is not theoretical: a recall defect in the arXiv path once passed the entire mocked suite while returning papers unrelated to the query. `tests/live_smoke.rs` asserts that a real query comes back on topic, that category narrowing does not silently empty the result, that a nonsense query returns nothing, that the OAI path fits the engine timeout, that an arXiv date window returns no paper outside it, that relevance order differs from recency order, that Semantic Scholar's citation order is non-increasing (skipped, not failed, when the shared rate limit answers 429), and that a cached engine answers a repeated query without the network. The live checks are about API contracts, not about exact result counts.

---

## 14. Directory Layout

- `Cargo.toml`
- `pyproject.toml` (maturin, `python` feature)
- `src/`
  - `lib.rs` (crate root, re-exports)
  - `model.rs` (Document / Author / DocIdentity / SearchQuery / SortOrder / Recency / Score)
  - `error.rs` (FetchError / SearchReport / ConnectorWarning / WarningKind)
  - `source.rs` (Source trait + SourceOutput / SourceNote + RatePolicy)
  - `engine.rs` (fan-out + concurrency cap + rate limit + fusion + dedup + date filter + cache assembly)
  - `normalize.rs` (URL normalization, date parsing, HTML cleanup, hashing)
  - `dedup.rs` (identity keys and grouping, DOI and arXiv normalization, MinHash-LSH near-duplicate)
  - `fusion.rs` (weighted RRF rank fusion + freshness, authority)
  - `cache.rs` (L1 moka + L2 redb, optional)
  - `ratelimit.rs` (per-source minimum-interval limiter)
  - `python.rs` (PyO3 bindings, `python` feature)
  - `sources/` (arxiv, arxiv_oai, semantic_scholar, rss, news, youtube, web, feed_common, http_retry)
- `tests/` (deterministic integration tests over mocked HTTP including `contract_test.rs`, plus `live_smoke.rs` which is `#[ignore]` by default)
- `.github/workflows/release.yml` (all-platform abi3 wheel build -> PyPI publish)

---

## 15. License

Apache-2.0

---

## 16. Changelog

### 0.3.0

New:

- **Semantic Scholar source** (`SemanticScholarSource`, Python `"s2"`): citation counts, venue, open-access PDF link, server-side date window, fields of study, minimum citations, optional key. Merges with arXiv results of the same paper.
- **Sort and date window** on `SearchQuery` (`sort`, `with_dates`, `with_recency`) and in Python `search(..., sort=, from_date=, to_date=, recency=)`. arXiv receives a `submittedDate` clause and `sortBy`; Google News receives `after:`/`before:` operators; other sources are filtered after fetching.
- **Warning kinds** (`ConnectorWarning.kind`): `empty`, `timeout`, `ratelimited`, `partial`, `unconfigured`, `notice`, `error`.
- **Weighted RRF** (`Engine::with_source_weight`, `fusion::fuse_weighted`, Python `source_weights=`).
- **Python**: cache (`cache="memory"|"disk"`, the wheel includes `cache-disk`), `user_agent`, `news_locale`, GIL released during search, `ValueError` for invalid input.
- Shared 429 handling (`RetryPolicy`, `Retry-After` in seconds or as an HTTP date) and an 8 MB response body cap.

Fixed:

- Documents whose URLs differ only by path case were merged into one.
- A document repeated inside one result list had its fused score multiplied (three copies scored about 0.0484 instead of 0.0164).
- One RSS feed failing next to healthy ones disappeared without a warning.
- A requested source without its key or feed list (or a misspelled source name) returned empty results with no warning; now `unconfigured` or `ValueError`.
- Python `search` held the GIL for the whole search, freezing other threads in the process.
- Identity merging depended on input order and missed DOI-only plus arXiv-only views of one paper; near-duplicate merging could merge documents with different DOIs or arXiv IDs.
- arXiv 429 backoff (3 s, 6 s, 12 s) slept past the 10-second source timeout; retries now stay inside a budget.
- The per-source `max_concurrency` was ignored, and the timeout did not cover the wait for the rate limiter.
- Failed or partial reports were cached for the full TTL.
- User-Agent strings were stuck at `/0.1`.
- An old 0.1.1 wheel committed under `dist/` was shipped inside the sdist (the 0.2.1 sdist on PyPI is 2.8 MB because of it). `Cargo.toml` now excludes `dist/`.

Behavior changes to check when upgrading:

- `ConnectorWarning` has a new `kind` field. Code that matched on message text keeps working, but `kind` is the stable interface.
- `SourceKind` has a new `Scholar` variant; exhaustive `match` statements need an arm.
- Python `Retriever(sources=[...])` raises `ValueError` for an unknown source name instead of ignoring it, and sources without keys now report `unconfigured`.
- Python `search` raises `ValueError` for `limit=0` or `limit > 1000`.
- A persistent arXiv 429 now ends as a `ratelimited` warning after about 3 seconds instead of a `timeout` after 10.
- The cache key keeps the query's case; `"RAG"` and `"rag"` are cached separately.
- Fused scores of documents repeated within one list are lower than before (by design).

Known limits: no pagination for Semantic Scholar, no request coalescing for identical concurrent searches, no conditional requests (ETag) for RSS, `expansions` and `include_content` are accepted but not implemented (a `notice` says so), `daily_quota` is not enforced, and there is no offline evaluation harness yet. OpenAlex and Crossref are candidates for later adapters.

