Files
news-platform/docs/AGGREGATOR_ARCHITECTURE.md
T
Artur MoreiraandPaperclip eff0aaa366 feat(frontend): add Cache-Control headers to all page routes (BIT-2261)
Set Cache-Control: s-maxage=60, stale-while-revalidate=300 on all page
routes to enable Cloudflare CDN caching per docs/architecture.md § 7.

Files updated:
- index.astro (homepage)
- article/[slug].astro (article pages)
- category/[slug].astro (category pages)
- noticias.astro (news listing)
- search.astro (search results)
- sitemap.xml.ts (sitemap)
- robots.txt.ts (robots)

This enables:
- CDN edge caching for 60 seconds (s-maxage)
- Serving stale content while revalidating for up to 300s (SWR)
- Improved TTFB for repeated requests (target: <30ms cache HIT)

Acceptance criteria:
✓ All page routes return correct Cache-Control header
✓ Cloudflare can cache responses with cf-cache-status: HIT
✓ TTFB improves to <30ms for cache HIT scenario
✓ Header values match architecture spec

Co-Authored-By: Paperclip <[email protected]>
2026-04-11 03:37:32 +00:00

421 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# News Content Aggregator — Architecture & Data Contract
**Status:** Active — delivered (BIT-709 to BIT-713)
**Last Updated:** 2026-04-02
**Related Issues:** [BIT-709](/BIT/issues/BIT-709) (epic), [BIT-711](/BIT/issues/BIT-711) (ingest), [BIT-712](/BIT/issues/BIT-712) (writer tools), [BIT-713](/BIT/issues/BIT-713) (integration)
## Executive Summary
Internal multi-source news content aggregator to reduce LLM read token cost by centralizing news sources (RSS, sitemaps, manual feeds, HTML fetch) into a single searchable database with deduplication and canonical linking. Rolled out in 4 phases over 4 weeks to maintain production continuity.
## 1. Core Data Schema
### Record Structure
```typescript
interface AggregatedArticle {
// Primary identifiers
id: string; // UUID
canonical_url: string; // Normalized URL (dedup key)
content_hash: string; // SHA256(headline + snippet) for dedup
// Content fields
headline: string; // Article title
snippet: string; // Short summary (100–200 chars)
body_preview: string; // First 300–500 chars
// Source metadata
source_name: string; // e.g., "Reuters", "Público", "RSS Feed Name"
source_type: "rss" | "sitemap" | "manual" | "html_fetch" | "api";
source_id: string; // Reference to source config
url: string; // Original/raw source URL
// Temporal data
published_at: timestamp; // Article publication date
ingested_at: timestamp; // When added to aggregator
refreshed_at: timestamp; // Last re-fetch/refresh
// Categorization
topic_tags: string[]; // e.g., ["politics", "tech", "finance"]
language: string; // ISO 639-1 (pt, en, es)
country: string; // ISO 3166-1 (PT, BR, US)
relevance_score: number; // 0–1, used for ranking
// Flexible metadata
metadata: {
author?: string;
section?: string;
word_count?: number;
image_url?: string;
tags?: string[];
[key: string]: any; // Source-specific fields
};
}
```
### Storage Backend
**MVP (Phase 1–2):**
- **SQLite** — Single-file database, no server dependency, suitable for ~500K–1M records
- **Location:** `bridge/data/aggregator.db` (checked into git-lfs or mounted volume in production)
- **Schema migration:** Use simple SQL DDL scripts in `bridge/src/aggregator/migrations/`
**Optimization (Phase 3+):**
- **PostgreSQL** if record volume exceeds SQLite performance limits
- Connection pooling via `pg` npm package
- Migration tool: `db-migrate` or Prisma (decide in Phase 2 based on team preference)
### Indexing Strategy
**Required indexes for query performance:**
- `canonical_url` — dedup lookup, exact URL query
- `content_hash` — dedup detection
- `published_at` — temporal filtering, sorting
- `source_id` — filter by source
- `topic_tags` — full-text/array search (PostgreSQL `GIN` index)
- `ingested_at` — retention policy cleanup queries
- Composite: `(source_id, published_at DESC)` — feed pagination
## 2. Deduplication & Canonicalization Rules
### Deduplication Algorithm
```
FOR each incoming article:
1. Compute content_hash = SHA256(headline + snippet)
2. Normalize URL → canonical_url:
- Lowercase domain
- Remove "www" prefix
- Strip tracking params: utm_*, fbclid, gclid, msclkid, etc.
- Remove fragment (#)
- Preserve article ID / path structure
- Example: "https://Example.com/article/123?utm_source=x"
→ "example.com/article/123"
3. Query database:
- SELECT COUNT(*) WHERE canonical_url = ? OR content_hash = ?
4. If record exists:
- Check published_at within ±24 hours
- If yes: DISCARD (duplicate)
- If no: KEEP (legitimate update/repost)
5. If new: INSERT into articles table
```
### URL Canonicalization Details
**Strip these query parameters:**
```
utm_source, utm_medium, utm_campaign, utm_content, utm_term,
fbclid, gclid, msclkid, mc_cid, mc_eid, twclid
```
**Preserve these (if present, include in canonical URL):**
```
id, article_id, story_id, post_id, (source-specific identifiers)
```
**Example transformations:**
```
https://bbc.co.uk/news/article-123?utm_source=twitter
→ canonical: bbc.co.uk/news/article-123
https://www.reuters.com/world/2026/article-456#comments
→ canonical: reuters.com/world/2026/article-456
https://tinyurl.com/abc123 (if resolvable)
→ canonical: (destination domain/path)
```
## 3. Retention & Refresh Policy
### Time-Based Windows
| Data Window | Age | Retention | Refresh Frequency |
|-------------|-----|-----------|-------------------|
| **Hot** | 0–7 days | 100% | Daily |
| **Warm** | 8–30 days | 100% | Weekly |
| **Cold** | 31–180 days | Sample (10%) | Monthly |
| **Archive** | 180+ days | DELETE or Archive (TBD) | N/A |
**Refresh logic:**
- Hot & Warm: On every ingest cycle, update `refreshed_at` for matched records
- Cold: Run monthly cleanup job; keep only random 10% sample (to preserve diversity)
- Archive: Decision in Phase 4 (cost vs. historical value)
### Cleanup Jobs
**Daily job (runs at 02:00 UTC):**
- Delete records with `ingested_at < NOW() - 180 days` (unless archived)
- Update statistics for query planner
**Weekly job (Mondays 03:00 UTC):**
- Sample cold data; mark/delete unselected rows
- Vacuum/ANALYZE database for performance
**Source-specific refresh:**
- RSS sources: Fetch every 6–12 hours (configurable per feed)
- Sitemap sources: Fetch weekly
- HTML fetch: On-demand or weekly
- Manual sources: When curator adds new entries
- API sources: Follow documented rate limits + backoff strategy
## 4. Phased Rollout (4 weeks)
### Phase 1: Foundation (Week 1) — Internal Only
**Goal:** Build and test aggregator core without pipeline changes.
**Deliverables:**
- SQLite schema + migrations
- Ingest service (RSS/sitemap/HTML fetch): BIT-711
- Query API endpoints (simple GET /aggregator/articles?q=...)
- Test data: 100–500K articles from 2–3 news sources
- Documentation: schema, deployment, monitoring
**Success Criteria:**
- Aggregator live on staging
- Dedup working: >80% of duplicate content detected
- API response time <500ms for typical query
- Zero production pipeline impact
**Risk Level:** None (internal only)
**Owner:** [BIT-711 assignee] + [BIT-710 architecture lead]
---
### Phase 2: Writer Integration (Week 2) — Opt-In
**Goal:** Enable writers to opt-in to aggregator as a content source; run parallel to existing workflow.
**Deliverables:**
- Writer tools UI/CLI: BIT-712
- Writer query interface (search, filter by topic/date/source)
- Sample output format for writers
- Runbook: "How to use aggregator in your writing workflow"
**Success Criteria:**
- Writers successfully query and fetch 10+ articles per request
- Aggregator results useful enough for 50%+ of queries
- Zero pipeline breakage
- <50ms latency for writer queries (cached)
**Risk Level:** Low (opt-in, no mandatory usage)
**Owner:** [BIT-712 assignee]
---
### Phase 3: Pipeline Integration (Week 3) — Default Source
**Goal:** Make aggregator the default content source in production pipeline.
**Deliverables:**
- Integration code: aggregator → writer agent input pipeline
- Fallback logic: if aggregator empty, fetch from direct sources
- Gradual rollout script: 10% → 50% → 100%
- Token cost measurement dashboard: BIT-713
- Rollback procedure (keep fallback active for 2 weeks)
**Rollout Timeline:**
- **Day 1 (Mon):** 10% of agent runs use aggregator
- **Day 3 (Wed):** 50% of agent runs
- **Day 5 (Fri):** 100% of agent runs
**Success Criteria:**
- **Token reduction:** 30%+ fewer read tokens per article (vs. direct fetch)
- **Error rate:** <5% (i.e., >95% of articles found in aggregator or fallback)
- **Latency:** <2s added to pipeline (total, including aggregator query + dedup)
- **Writer satisfaction:** No complaints about article quality/relevance
**Rollback Trigger:**
- Error rate >10%
- Token reduction <15%
- Any production incident linked to aggregator
**Risk Level:** Medium (default usage, but with fallback)
**Owner:** [BIT-713 assignee] (pipeline integration + monitoring)
---
### Phase 4: Optimization (Week 4+) — Fine-Tuning
**Goal:** Optimize based on production data and cost analysis.
**Tasks:**
- Analyze token savings per source/topic
- Tune retention policy: should cold data be archived or deleted?
- Evaluate relevance scoring algorithm (TF-IDF vs. source authority vs. publish decay)
- Cost breakdown: storage, CPU, vs. API token savings
- Update documentation with learnings
**Deliverables:**
- Cost/throughput trade-off analysis
- Updated retention policy (if changing)
- Relevance scoring algorithm (if implemented)
- Tuning guide for operations team
**Owner:** Xika (Flow Challenger) + [BIT-713 assignee]
## 5. Dependencies & Assumptions
### Hard Dependencies
- **BIT-710** (this document): Schema + plan approval (must complete before BIT-711 starts implementation)
- **BIT-711** (ingest): Must complete before Phase 2
- **BIT-712** (writer tools): Required for Phase 2
- **BIT-713** (integration): Required for Phase 3
### External Dependencies
- **News sources:** RSS feeds, sitemaps, APIs must be available and accessible
- **Database:** SQLite (built-in, no external dependency for MVP) or PostgreSQL (Phase 3+ optional)
- **HTTP client:** Node.js `node-fetch` or similar (already in bridge project)
- **Writer agent infrastructure:** Must support HTTP queries to aggregator API
### Assumptions (to validate in Phase 1–2)
- RSS/sitemap feeds are stable and parseable
- HTML fetch + basic text extraction sufficient (no JavaScript rendering)
- Single SQLite database sufficient for 500K–1M records on single node
- Writers prefer aggregator results over direct API fetches (will validate in Phase 2)
- 30%+ token reduction is achievable (baseline: measure in Phase 1)
## 6. Open Questions & TBD
### Content Relevance Scoring
**Question:** How should `relevance_score` be calculated?
**Options:**
1. **Manual tagging:** Human curators tag topics (simple, labor-intensive)
2. **TF-IDF:** Compute term frequency within article + inverse document frequency (standard, requires text processing)
3. **Source authority:** Weigh sources by historical reliability (domain knowledge, tunable)
4. **Temporal decay:** Newer articles scored higher; decay over days (encourages fresh content)
5. **Hybrid:** Combination of above
**Recommendation:** Start with simple recency decay + source whitelist (Phase 1). Implement TF-IDF in Phase 4 if time permits.
---
### Cold Data Archival
**Question:** What to do with records 180+ days old?
**Options:**
1. **Delete:** Free up storage, faster queries. Lose historical context.
2. **Archive to S3:** Keep for audit; slower queries. Added cost.
3. **Sampling:** Keep 10% sample (statistically representative, compromise)
**Recommendation:** Delete in Phase 1–2 (keep cold window at 180 days). If Phase 3 analysis shows historical value, implement S3 archival.
---
### Multi-Language Support
**Question:** Should aggregator support multiple languages from day 1?
**Options:**
1. **Portuguese + English:** Support both PT and EN by default
2. **Portuguese only:** Filter to PT sources, add EN later
3. **Configurable:** Let team choose per deployment
**Recommendation:** Portuguese + English (MVP). Aggregator stores `language` field; filtering is downstream (writer config or query param).
---
### Article Update Strategy
**Question:** If an article is updated (e.g., title changes, breaking news update), how should aggregator handle it?
**Options:**
1. **In-place replacement:** Update existing record's `body_preview` and `refreshed_at`; keep same ID
2. **New record:** Treat as new article, mark old as `superseded_by`
3. **Hybrid:** If headline changes significantly, treat as new; if only body updates, replace
**Recommendation:** In-place replacement (Phase 1). Content hash includes headline + snippet, so major updates will fail dedup and create new records anyway. Revisit in Phase 4 if issues arise.
## 7. API Contract (Preview)
**Ingest endpoint (internal only):**
```
POST /api/aggregator/ingest
{ source_type, source_id, articles: [{ headline, url, published_at, ... }] }
→ { inserted: N, duplicates: M, errors: [...] }
```
**Query endpoint (writer-facing):**
```
GET /api/aggregator/articles?q=search_term&topics=politics&limit=20&offset=0
→ { articles: [...], total: N, has_more: bool }
```
**Health/stats endpoint:**
```
GET /api/aggregator/stats
→ { total_records, by_source: {...}, last_refresh: timestamp, error_count: N }
```
(Full endpoint specs in BIT-711 implementation.)
## 8. Success Metrics & KPIs
**Phase 1 (Foundation):**
- ✓ Aggregator online with 100K+ articles
- ✓ Dedup rate >80%
- ✓ API response <500ms
**Phase 2 (Writer Integration):**
- ✓ 50%+ of test writers use aggregator at least once
- ✓ Average query returns 10+ useful articles
- ✓ Writer satisfaction >4/5 stars
**Phase 3 (Pipeline Integration):**
- ✓ 30%+ token reduction per article
- ✓ Error rate <5%
- ✓ No production incidents (or rollback complete)
**Phase 4+ (Optimization):**
- ✓ Documented cost/throughput analysis
- ✓ Tuned retention policy in place
- ✓ Team confident in operations
## 9. Implementation Roadmap
```
Week 1 (Phase 1 — Foundation)
├─ Mon: Approve this architecture (BIT-710)
├─ Mon-Tue: Implement ingest service (BIT-711)
├─ Wed: Populate test data
├─ Thu-Fri: API + monitoring
└─ Fri: Ready for Phase 2
Week 2 (Phase 2 — Writer Integration)
├─ Mon-Tue: Writer tools UI (BIT-712)
├─ Wed-Thu: Integration + testing
├─ Fri: Pilot with test group
└─ Fri: Ready for Phase 3
Week 3 (Phase 3 — Pipeline Integration)
├─ Mon: Start gradual rollout (10%)
├─ Wed: Scale to 50%
├─ Fri: Full rollout (100%)
└─ Week 3: Monitor + measure (BIT-713)
Week 4+ (Phase 4 — Optimization)
├─ Mon: Analyze data + costs
├─ Tue-Wed: Implement improvements
├─ Thu-Fri: Document + handoff to ops
└─ Ongoing: Maintain + tune
```
## References
- **Epic:** [BIT-709](/BIT/issues/BIT-709) — News Project aggregator
- **Ingest implementation:** [BIT-711](/BIT/issues/BIT-711)
- **Writer tools:** [BIT-712](/BIT/issues/BIT-712)
- **Pipeline integration:** [BIT-713](/BIT/issues/BIT-713)
- **News platform codebase:** `/opt/bitreport/news-platform/bridge`
---
**Document prepared by:** Xika (Flow Challenger)
**Date:** 2026-04-02 08:36 UTC
**Status:** Ready for board/team review before Phase 1 implementation