Skip to content

Ingestion pipeline lift: news to Rust

Status: plan only (2026-12-04). Nothing is built. Owner decision, 2026-12-04: “The ingestion pipeline: leave for now. That’s a lift we need a plan for.” This page is that plan. It changes no repository, service or setting. Tracking issue: nyuchi/nyuchi-docs#183. It depends on, and must be read with, MongoDB: self-hosted primary, Atlas as edge.

Evidence marks: Verified (read from a repository or probed read-only on 2026-12-04, source named) and Unverified (not checked).

  1. Do not start with the 12.7k-line port. Start with three small, independently shippable things that cut risk whichever way the lift goes: record real inputs, fix the fundi enrichment silent failure, and add an external dead-man alert for the pipeline (section 9).
  2. Port the writer first, the readers after, and keep collection shapes frozen. This is the rule from the Rust data-processing inventory (bundu-standards PR 180, standards/rust-data-processing/INVENTORY.md, row 3 and section 4): ingestion, the MongoDB news schema, the news gateway, the reader, the Nyuchi API news routers and data-infra/scripts/news share one database and move together.
  3. The new pipeline writes to the self-hosted primary, so it lands at milestone M7 of the MongoDB plan, not before. Until then it can be built and shadow-tested against a scratch database on the lab primary (M2 of the MongoDB plan) without touching Atlas or production.
  4. Move off Fly at the same time as the language change, not before. The target host is Coolify on gondor (Apps VLAN 20) or a Proxmox LXC container, one Rust service plus one Rust Worker for the enrichment contract.
  5. Estimate: about 14 to 18 working weeks for one engineer, delivered as about 20 small steps (section 10). The first four steps are days each and are worth doing even if the lift is later cancelled.
Piece Facts Source
fly-worker Python 3.12, FastAPI, APScheduler, Motor, trafilatura. About 11.2k lines under src/ (12.7k with scripts, per the inventory). Fly app mukoko-news-api, region jnb, one 2 GB shared machine, auto_stop_machines = "off", min_machines_running = 1, health check /health every 30 s. Live on 2026-12-04: /health returned healthy, mongodb: connected, heartbeats fresh for every job, stalled: [] fly-worker/fly.toml, GET https://mukoko-news-api.fly.dev/health
Jobs (cadence) rss_collector every 15 min (tunable); newsdata_collector every 6 h at :30; newsdata_sources; engagement 5 min; trending 30 min; health_checker 6 h; image_backfill 10 min; country_backfill; journalist_link; markdown_backfill 5 min; fulltext_fetch; byline_backfill; cleanup 03:00; org_bootstrap 04:00; domain_observer (a long-lived change stream over news, engagement, entity) src/scheduler.py, /health
Services (pure-ish logic) content_cleaner (623 lines), rss_parser, link_reputation, domain_guard, byline/byline_identity, publishing_houses, source_country, discovery, og_image, article_ids (UUIDv7 for new articles only), news_events (dual-write of news.article.* events to the Nyuchi API, off unless NEWS_EVENTS_ENABLED=true), watchdog, vector_search src/services/
HTTP surface GET /health; bearer-token POST /trigger/{collect, newsdata, newsdata-sources, byline-backfill, enrich-backlog, markdown-backfill, country-backfill, byline-link, fulltext-fetch} (FLY_TRIGGER_TOKEN, fail-closed 503 if unset) src/main.py
Tests 55 test files, about 11k lines, plus the incident write-up inventory row 3
enrichment-agent (fundi-enrichment-agent) TypeScript Cloudflare Worker with a Durable Object agent; POST /api/enrich ({articleIds, source}, bearer token), POST /api/enrich/backlog, POST /api/enrich/org, GET /health, GET /api/agent/status; cron */5 * * * * drains a backlog; Workers AI through the fundi AI Gateway for keywords, quality, classification, summaries and 1024-dim embeddings; writes enrichment into news.articles. Live: /health returned {"status":"ok","auth":"configured"} enrichment-agent/src/index.ts, wrangler.jsonc, probe
image-worker Cloudflare Worker, image proxy at assets.mukoko.com/i/* (about 4.9k lines for agent and image worker together) inventory row 3b
Event dual-write After each news.articles write the pipeline can POST news.article.* to the Nyuchi API; fundi emits news.article_embedding.generated. Inert unless owner sets NEWS_EVENTS_ENABLED README.md
Incident 2026-07-05: ingestion stalled silently for 53 days. Root cause: Motor client with serverSelectionTimeoutMS and a pool of 10 but no socket, connect or wait-queue timeouts; a dead socket drained the pool; /health itself hung; nothing exited. Detection: none docs/incidents/2026-07-05-pipeline-stall.md
Component What it does with the news database Size and runtime (inventory)
mukoko-dev/mukoko-news-gateway (news.mukoko.dev) Public news API and MCP, native driver under nodejs_compat, crons */5 and 0 */6, D1 audit, also writes identity/entity from WorkOS 24.7k lines TS, Worker, row 15, medium-high risk
mukoko-dev/mukoko-news (news.mukoko.com) Reader on Vercel, server actions read Mongo directly about 14.5k server-side lines, 126 test files, row 16
nyuchi/nyuchi-api news routers (news.py, news_analytics.py, news_related.py, news_article_detail.py, news_topics.py, news_events.py) and rust/crates/core/src/news The API that the apps are moving onto (/v1/news/*), $vectorSearch related articles, analytics, events part of the 84k-line Python gateway; Rust crate exists
nyuchi/data-infra scripts/news (newsmap.py, backfill.py, parity.py) Map a document to news events; replay Atlas into the log; compare search results (the Doris half of parity.py is obsolete since Doris was removed on 2026-11-22) small, Python, tests offline
MongoDB news database 11 catalogued collections (articles, articleSnapshots, categories, comments, feedSources, journalists, newsMediaOrganizations, publisherRateLimitTiers, publisherVerifications, sourceCategoryTrust, sourceScoreHistory) and 20-odd unvalidated ones (articleLikes, articleSaves, articleViews, pipelineLogs, pipelineState, and others) news was 2.42 GB on disk at 2026-10-02 (data-infra)
Four other copies of the “fundi” agent kweli/workers/fundi-ingestion, mongodb-mcp, agent-tools/fundi, kweli-mcp: inventory Wave 0 says decide one fundi implementation before porting five inventory section 2

Rule: Rust for anything that processes data; Node is a build tool, never a service runtime. Layout follows the estate’s core, origin and edge split: pure core with no I/O, origin that owns I/O, a thin edge.

news/ (one workspace; repo: nyuchi/nyuchi-news or inside nyuchi-servers-api, decision D2)
crates/
news-core/ pure: cleaner, URL and domain guard, byline, link reputation, trending score,
article id (UUIDv7), canonical URL, dedupe keys, event mapping. No network, no clock
except an injected Clock. This is where 70% of the Python tests go.
news-contract/ the shared HTTP contract with fundi: EnrichRequest, EnrichResponse, Backlog,
error codes, and a golden JSON file. Used by BOTH the pipeline and the agent.
news-collectors/ RSS (feed-rs), newsdata.io client (reqwest), full-text fetch (readability port or
a vetted extractor, decision D5), discovery
news-store/ the `mongodb` crate: collections, indexes (the catalogue is the source), idempotent
upserts, change stream wrapper, bounded timeouts everywhere
news-worker/ binary: scheduler (tokio, cron expressions), axum for /health /metrics /trigger/*
fundi/ (phase 3) the enrichment agent as a Rust service: calls Workers AI and the AI Gateway
over HTTPS REST, writes enrichment with the same store crate

Choices and the reasons:

  • Scheduler: tokio with an explicit job table (name, interval or cron, max_runtime, overlap = skip), not a library with hidden state. Every job records a heartbeat row and a Prometheus gauge. A job that exceeds max_runtime is cancelled and counted.
  • Mongo: the mongodb crate, with the same bounds the incident taught: connect_timeout, server_selection_timeout, max_idle_time, max_pool_size, and a per-operation timeout (client-side operation timeout) so no operation can wait forever. A test fails the build if a collection call is made through a client without those options.
  • Idempotency: the document key stays as it is (dedupe by feedSourceId + sourceGuid and externalUrl; _id UUIDv7 for new articles), enforced by unique indexes and upserts so two overlapping runs or a retry cannot create a duplicate. Event emission goes through an outbox collection written in the same operation as the article and drained by a publisher, so an event is not lost when the process dies between the write and the POST (the Python code today emits after the write and swallows failures).
  • Backpressure: bounded channels between fetch, clean and write stages; a per-host semaphore and a per-source token bucket (politeness to publishers); a global in-flight cap; a circuit breaker per feed (open after N consecutive failures, half-open probe with jittered backoff). A slow Mongo makes the fetch stage wait, not buffer unbounded memory.
  • Errors: one error type per crate (thiserror), every error classified transient (retry with backoff), permanent (record on the source, never retried within the run) or fatal (exit non-zero so the supervisor restarts). Panics are caught at the job boundary and counted.
  • Observability: tracing with JSON logs to Loki; /metrics for Prometheus (jobs run, last success timestamp, articles written, duplicates skipped, per-source failures, queue depths, enrichment backlog age, Mongo latency histogram); /health keeps the current contract (status, mongodb, per-job heartbeat_age_seconds, stalled, restart_pending) so the reader app and the existing probes keep working; an external dead-man alert: time() - last_article_created_timestamp > 3 * interval pages the owner (this is the alert whose absence caused the 53-day stall).
  • Security: bearer tokens for /trigger/* compared in constant time; outbound HTTP through one client with an SSRF guard (reject private, link-local and loopback ranges, the Python domain_guard intent); response size and redirect caps; secrets from Durin or erebor at boot, never in an environment file in the repository; no 1Password in the dev path.
  • Edge Worker for enrichment contract (until phase 3): keep the current TypeScript Worker serving the HTTP contract unchanged; the Rust pipeline is only a different caller. The shared news-contract crate generates a JSON Schema and a golden request and response that the TypeScript agent’s tests also load, so the two sides cannot drift.

The failure: notify_enrichment_worker returns early when FUNDI_ENRICHMENT_URL is empty, so a missing value disables all enrichment while ingestion looks healthy. The Python code now prints one warning per process and fly.toml carries the URL in [env] to prevent the missing value; a 401 (token mismatch) is also logged only, throttled to about hourly. Articles then sit unenriched with no alert.

Fix, in order of cost:

  1. Now, in Python (small, safe, reversible): make an empty FUNDI_ENRICHMENT_URL or FUNDI_ENRICHMENT_TOKEN a boot failure when ENVIRONMENT=production, and expose enrichment_backlog_age_seconds (age of the oldest article with no enrichment fields) on /health. Add one external alert on it. This is the first thing to do and does not wait for the lift.
  2. In the Rust pipeline: configuration parsing makes both values required (a missing or empty value fails news-worker --check and the service refuses to start), the notifier returns a typed result, and an un-enriched article is a metric, not a log line: news_unenriched_oldest_age_seconds with an alert at 30 minutes.
  3. The contract is one crate (news-contract), with a contract test run against the real agent in CI and a --probe mode that calls /health and a dry-run /api/enrich with an empty list.
  4. Consolidate the fundi agent (inventory Wave 0 item 3): one Rust implementation instead of five TypeScript copies, in phase 3 of this plan; the Cloudflare-specific bindings (env.AI, Durable Object alarms) become REST calls to Workers AI and the AI Gateway from a Rust service on the same host as the pipeline, with its own scheduler replacing the */5 cron.
MongoDB plan milestone News lift step that needs it
M0 verified Atlas dump Before anything: the news dump is the parity baseline and the rollback
M2 lab primary with mongot The Rust pipeline can write a shadow database news_shadow here from the first day it runs; the Python pipeline is not touched
M3 three members, backups Soak the Rust pipeline against a database that behaves like production (failover drill under ingest load)
M4 anduin Atlas to primary Gives the lab a live copy of news, so shadow output can be compared with the real, current corpus
M5, M6 other domains flip Not blocked by news; the news lift must not start flipping anything until the other domains have been stable
M7 news domain flip The Rust pipeline becomes the writer; reader and gateway read the edge; anduin flips for news to primary to Atlas; search from lorien

Consequences: (a) no Python-to-Rust change and a Mongo move in the same week; they are separate flips with separate rollbacks; (b) the Python pipeline keeps writing to Atlas until M7 and is the system of record during the shadow period; (c) the Rust pipeline’s MONGODB_URI is a plain config value so the same binary runs against the lab, the primary and, in a rollback, Atlas.

  1. Second app, not a replacement: deploy the Rust service as a second, separately named app (LOTR name under nyuchiservers.com, decision D4) on gondor, with its own scheduler and its own Mongo user that can write only news_shadow and nothing else (least privilege makes a mistaken URI harmless).
  2. The Python pipeline continues to write news in Atlas. The Rust pipeline fetches the same feeds (not a copy of the Python output) and writes news_shadow on the lab or the primary. domain_observer’s equivalent runs against the shadow only.
  3. A comparison job joins news.articles (replicated copy) and news_shadow.articles by feedSourceId + sourceGuid and reports, per field, the number of identical documents, allowed differences (timestamps within a window, ids, createdAt) and real differences. A diff allow-list is itself reviewed and versioned.
  4. Enrichment: for the shadow period fundi enriches only the live corpus. Shadow articles are compared before enrichment fields; embeddings get an offline check (cosine similarity of the same article’s vectors from both paths is not expected to change, because the agent is unchanged).
  5. Cleanup is a drop of news_shadow, never of news.
  • Record real inputs first (step 1 of the plan). A small recorder in the Python pipeline (or a transparent proxy in front of it) stores, per fetch, the request URL, status, headers and raw body for every feed and newsdata.io call for 7 days (about 54 countries’ feeds at 15-minute cadence: tens of thousands of bodies; store as compressed content-addressed objects in a private R2 bucket, plus a manifest in the repository containing hashes, not content). Publishers’ text is third-party content: the bucket is private, access is limited, and fixtures in the repository are hashes plus a few short, licensed or synthetic samples.
  • Golden outputs: run the Python code on the recorded bodies with a frozen clock and a fake store, and store the produced documents as golden JSON. The Rust news-core and news-collectors must produce the same documents byte for byte for every recorded body, except fields on the allow-list.
  • Property tests for the cleaner and the canonical URL (idempotence: clean(clean(x)) == clean(x); never longer than the input plus markup; no HTML in output) and for the dedupe key.
  • Failure replay: recorded bad inputs (malformed XML, huge bodies, redirect loops, wrong encodings, a hung socket via a test server) must degrade without crashing or stalling. The 2026-07-05 signature is a test: a Mongo server that accepts a connection and never answers must make /health report degraded within the timeout and the process exit or recover.
  • Schema parity: every collection’s $jsonSchema validator and index set from mongo_catalog.json is applied to the shadow database by the Rust news-store and diffed against production (names, keys, uniqueness, TTL).
  • Reader parity: the news gateway and the API routes are run against a database populated from the shadow and compared with the same requests against the live one (the *_golden.py scripts and news_golden.py in the API repositories are the fixtures).

8. Scheduling, hosting and the move off Fly

Section titled “8. Scheduling, hosting and the move off Fly”
  • Host: Coolify on gondor (Ubuntu 24.04 VM, Apps VLAN 20) or a dedicated LXC container. gondor could not start on 2026-11-22 because VT-x was disabled in the BIOS (Unverified whether it is fixed); if it is still blocked, use an LXC container (no VT-x needed). One instance, restart: always, a /health check, resource limit 2 GB.
  • No inbound public surface: /trigger/* is reachable only from the LAN and from callers on the Workloads or Apps VLAN by service binding; the reader’s “refresh” action and the gateway’s /api/refresh and drain_enrichment_backlog MCP tool call the API, which calls the pipeline, so no token is shared with Vercel or a Worker. (Today the same FLY_TRIGGER_TOKEN gates all trigger endpoints and lives in the reader and the gateway; rotating it for one rotates it for all.)
  • Latency to Mongo: the pipeline and the primary are on the same LAN, which is the one workload for which the home placement is a clear gain over Fly jnb to Atlas af-south-1. Its inputs are internet fetches whose own latency dominates.
  • Egress and politeness: one stable egress IP; a published user agent with a contact page; respect robots.txt and Retry-After; per-host rate limit.
  • Scheduling: one leader. If a second instance is ever run, a Mongo lease document (with TTL and a fencing token) decides who runs each job; for now replicas = 1 and the job table is in code.
  • Availability: home line and power are single points (see the MongoDB plan R3). Honest consequence: ingestion can stall when the line is down; the dead-man alert and a catch-up behaviour (jobs fetch since the last success) bound the harm. Missed RSS items beyond the feed’s own window are lost: that is a decision (D6) on whether a small always-on fetcher stays on a cloud host.
  • Image worker and enrichment Worker: stay on Cloudflare during phases 1 and 2 (they serve the edge by design); image-worker becomes a workers-rs Worker in a later step; fundi moves in phase 3 (section 4).
Step Action Rollback
R0 (no risk) Recorder, golden outputs, dead-man alert, the Python fundi boot-failure fix Remove the recorder
R1 shadow Rust service writes news_shadow; comparison report daily; Python unchanged Stop and drop the shadow
R2 per-collection writer flips After 7 clean days: move one low-traffic collection at a time to the Rust writer (pipelineLogs, pipelineState, sourceScoreHistory, then feedSources, then articles) behind a per-collection flag read by both writers (only one writes a collection) Flip the flag; the Python writer is still running and idempotent
R3 articles on the primary (M7) With the MongoDB plan M7: the Rust writer writes articles to the primary; anduin feeds the edge Flag back to the Python pipeline and to Atlas (it stays current through anduin)
R4 retire Python Two weeks of clean running: scale the Python Fly machine to zero (snapshot first), then destroy at the owner’s word Scale it back up (minutes)
R5 readers and routers Gateway and reader move onto /v1/news/*; gateway’s identity and entity writes move behind the API; Rust news routes take over Per-route flag

No step flips the writer and the database in one change; no step touches the schema.

Sizes: S is one to three days, M is one to two weeks, L is three or more weeks. One engineer (the owner’s agents plus review), including tests, runbook updates and review time.

# Step Size Ships on its own
1 Python: fundi URL and token required at boot, enrichment_backlog_age_seconds on /health S Yes (closes the silent failure)
2 Dead-man alert on newest article age and per-job heartbeat age (Prometheus rule, monitoring addon) S Yes
3 Input recorder and the private R2 fixture store S Yes
4 Golden outputs from Python over recorded inputs; freeze the allow-list S Yes
5 Decide D1 to D6 below S n/a
6 news-contract crate plus agent-side contract test (TypeScript side loads the golden) S Yes
7 news-core part 1: article id, canonical URL, dedupe keys, event mapping, golden-tested M Library
8 news-core part 2: content_cleaner, byline, link_reputation, domain_guard, publishing_houses with property tests M Library
9 news-store: collections, indexes from the catalogue, bounded timeouts, idempotent upserts, outbox M Library
10 news-collectors: RSS and newsdata.io, per-host limits, circuit breaker M Library
11 news-worker skeleton: scheduler, /health with the current contract, /metrics, --check and --probe M Binary, no jobs
12 Jobs batch 1: rss_collector, newsdata_collector, cleanup M Shadow-ready
13 Shadow deployment on the lab and the comparison report (needs MongoDB plan M2) M Yes
14 Jobs batch 2: engagement, trending, health_checker, image_backfill, journalist_link, byline_backfill, country_backfill, markdown_backfill, fulltext_fetch, org_bootstrap, domain_observer equivalent L Yes, behind flags
15 Failure replay suite and the 2026-07-05 stall test S Yes
16 Per-collection writer flips (needs MongoDB plan M3 and M4) M Yes
17 News domain flip with the MongoDB plan M7; retire Python M Yes
18 Gateway: identity and entity writes behind the API; gateway onto /v1/news/* (the Rust news crate) L Yes
19 Fundi consolidation to one Rust service (phase 3) L Yes
20 Reader (mukoko-news) off direct Mongo and off Vercel Node runtime; image-worker to workers-rs L Yes

Total: roughly 14 to 18 weeks of focused work (steps 1 to 17 are about 9 to 12 weeks; 18 to 20 are the other 5 to 6). These are estimates from line counts and the existing test corpus, not from a spike; do a one-week spike on steps 7 and 8 and re-estimate.

Risk Mitigation
A second silent stall (the 53-day class) Step 2 first; per-operation timeouts; the stall test; external alert
Behaviour drift in the cleaner or the dedupe (reader sees different articles) Golden outputs over real inputs; allow-list reviewed; per-collection flips
Rust extraction quality differs from trafilatura Decision D5; keep a golden set; fall back to calling a small Python sidecar only if required and short-lived
Two migrations at once (language and database) hide each other’s faults Separate flips, different weeks, shadow database first
Home availability See MongoDB plan R3; catch-up fetch windows; D6
Third-party content in fixtures Private bucket; hashes in the repository; short, licensed or synthetic samples only
Enrichment Worker cost and rate limits during backlog drains Keep the agent’s own spend guards and ledger; the Rust notifier batches at the existing MAX_BATCH of 50
Five fundi copies diverge while the work is on hold Inventory Wave 0 decision (one implementation) is step 5
# Decision Recommendation
D1 When the lift starts, given it depends on MongoDB plan M2 and M3 Start steps 1 to 4 now (they are cheap and independent); the rest after M2
D2 Repository: new nyuchi/nyuchi-news workspace, or inside nyuchi-servers-api (one Rust home) The inventory warns about two Rust workspaces with the same layout; pick one home first
D3 One fundi implementation: which repository owns it (inventory Wave 0) This pipeline’s enrichment agent is the live one; consolidate into it
D4 LOTR names for the pipeline and its host (for example the pipeline, the shadow app) Owner to name; names are not generic
D5 Full-text extraction in Rust: a Rust extractor, or accept a short-lived Python sidecar Spike in step 8
D6 Is an always-on cloud fetcher required while home availability is a single point Decide after MongoDB plan M1 measurements
D7 Whether NEWS_EVENTS_ENABLED (the event log dual-write) is switched on before or after the lift After; do not add a third moving part
  1. Open the four S-sized steps (1 to 4) as issues in mukoko-dev/mukoko-ingestion-pipeline. They are Python-side, additive and do not need the owner’s lift decision.
  2. Ask the owner for D1 to D3 in one message.
  3. Do not write Rust code, create the new app, or touch Atlas until MongoDB plan M0 (the verified dump) and M2 (the lab) exist.
  • Repository reads (2026-12-04): mukoko-dev/mukoko-ingestion-pipeline (README.md, fly-worker/fly.toml, src/scheduler.py, src/main.py, src/services/enrichment_notifier.py, src/services/mongodb.py, src/services/article_ids.py, enrichment-agent/src/index.ts, wrangler.jsonc, docs/incidents/2026-07-05-pipeline-stall.md); nyuchi/data-infra scripts/news, docs/runbooks/news-vertical.md; mukoko-dev/mukoko-news-gateway; nyuchi/nyuchi-api routers; nyuchi/api-gateway db/spine/catalog/mongo_catalog.json.
  • bundu-labs/bundu-standards PR 180: standards/rust-data-processing/INVENTORY.md (read with gh pr diff 180; the owner’s clone was not touched).
  • Read-only probes: https://mukoko-news-api.fly.dev/health, https://fundi-enrichment-agent.nyuchi.workers.dev/health.