Oshan Ranasinghe

Work / Software / DeepFeed AI

Applied AI • Personalized research platform

DeepFeed AI

A research feed that explains every pick, and an assistant that cites its sources or says it doesn't know. I built it alone, from first commit to production. It finds AI and ML reading for each user, ranks it against their interests, learns from their feedback and keeps their sources in a private library. Every answer is grounded, cited and checked against a 143-question evaluation set before release.

Role

Sole engineer: product, backend, ML, frontend, infra

Timeline

Jun – Oct 2026 · 178 commits · 45 PRs

Stack

FastAPI · Celery + RabbitMQ · PostgreSQL + pgvector · Next.js 14

Status

RAG v1.2 released · deployed from CI

Every card carries the reason it was picked

The "% match" badge is semantic relevance between the item and the reader's interests. The full score is five weighted factors, saved with the recommendation as a trace, so the explanation is read back from stored data rather than written after the fact.

arXivPaper2dNew87% match

Draft-model cascades for faster speculative decoding

A short summary written at ingest, sized to the reader's chosen depth, so the card can be judged without opening it.

Large Language ModelsInference
Why this recommendation?
Relevance0.87×0.60
Credibility0.80×0.10
Freshness0.92×0.12
Novelty0.70×0.10
Feedback0.50×0.08
Final score, saved as a RecommendationTrace0.82
FIG 01 — A feed card and its ranking trace (sample item)

01 — Problem

More sources don't make a better reading list

An engineer following AI research has arXiv, lab blogs, newsletters and news sites to keep up with. Collecting all of it is easy. Deciding what deserves an hour of attention today is the hard part, and most feeds hand that decision back to the reader.

The tools that do decide tend to hide their reasons, so a bad pick can't be corrected. Chat assistants have the opposite problem. They answer confidently whether or not the reader's sources support the answer.

1

Relevance is personal

"Reinforcement learning" means different papers to a robotics student and a quant. A shared ranking serves neither of them well.

2

Opaque ranking can't be corrected

When a reader can't see why an item surfaced, their feedback has nothing to act on. The model drifts and they lose trust in it.

3

Ungrounded answers are worse than none

A fluent answer about the wrong product version costs more than "I don't know". The assistant has to know when to refuse.

02 — Solution

Three surfaces, one model of the reader

DeepFeed splits the job into a feed that decides, a library that remembers and an assistant that answers. All three share the reader's interests, feedback and saved sources, so a signal from one improves the others.

Feed

Discover, then explain

A research agent searches the reader's sources and the open web, then reads, summarizes and ranks what it finds.

  • Live "Discover Now" runs with streamed progress
  • A "Why this recommendation?" breakdown on every card
  • Like, save and "not relevant" teach the ranking

Library

Keep the evidence

URLs, PDFs, DOCX, HTML, Markdown and notes become immutable documents. Each one is chunked, embedded and searchable.

  • Durable ingestion that survives worker crashes
  • Document graph and a 3D vector-space map
  • Save any feed item straight into the library

Ask DeepFeed

Answer with citations

A streaming assistant answers from the feed and library together, with an inline citation in every paragraph.

  • Routes each question to the feed, the library or both
  • A support check blocks answers the evidence doesn't state
  • Editable long-term memory of the reader
The loop

Interests → research plan → discovery → ranking → feedback → learned preferences. Agents run the loop nightly. Each change they make is saved as an AdaptationEvent with a reason, a confidence and before/after values, so the feed's drift can be audited.

03 — Architecture

A modular monolith, with durable work around it

One FastAPI codebase serves the API and also runs in the Celery workers, so a ranking pass behaves the same whether a request or the scheduler starts it. PostgreSQL holds everything: relational records, full-text indexes, 1536-dimension embeddings, job state and the dispatch outbox. RabbitMQ only carries messages. A lost message can always be recovered from the database.

Video — Architecture walkthrough: layers, boundaries, and how requests flow through the system

DeepFeed system architecture: edge, API, application services, async workers, storage, external providers, observability and deliveryEDGE + CLIENTAPIAPPLICATION SERVICESASYNC EXECUTIONSTORAGEEXTERNALOBSERVABILITYDELIVERYBrowserFeed, Library, AskNginxTLS · CSP · edge limits · unbuffered SSENext.js 14 frontendApp Router · React Query · Zustand · D3 graph/api/* · prefix strippedFastAPI · Python 3.12 · PydanticMiddleware: trace id + traceparent · audit · rate limit · Prometheus metrics · bounded bodies · JWT (Argon2)/auth /feed /content/discover /feedback /agent /knowledge/* /assistant/chat/stream /admin /health /metricsDiscoveryDiscover Now pipelineCoverage-gap web searchSource lifecyclePer-user content poolLLMRanking engineSemantic relevance5 weighted factorsHard relevance floorRecommendationTraceEMBEDAdaptation agentsUserModelingAgentResearchPlanningAgentReflectionAgentAdaptationEventsLLMKnowledgeDurable ingestionHybrid search + RRFContext budgetingIndex lifecycleEMBEDAssistant (RAG)LLM routerSpeculative retrievalGrounding + support checkMemory · SSE streamLLMCelery Beathourly · 30 min · 02:00 · 03:00RabbitMQ 3.13default · discovery · processing · ranking · adaptationCelery workers · same imagelate ack · DB leases + fencing tokensrun the same servicesasync SQLAlchemy 2outbox → publish due work / 15 sPostgreSQL 16 + pgvectorusers · interests · recommendations + traces · feedback · adaptation eventsdocument versions · chunks · 1536-d embeddings · full-text tsvectoringestion jobs · dispatch outbox · conversations + citation snapshotsknowledge_raw volumeOriginal source bytes, never rewrittenChecksums kept in PostgreSQLRe-index never refetchesContent sourcesRSS · Atom · arXivWeb search backend · URLsOpenAItext-embedding-3-smallgpt-4o-mini · answersgpt-4.1-mini · support checkAnthropicclaude-haiku-4-5 · fallbackbreaker: 3 fails → skip 30 sSMTP verification · resetsOTLPJaegertracesservice mapPrometheusAPI · workerbeat · PG · MQGrafanaOne trace per Discover journeyDashboards saved in the repoGitHub Actionsruff · tests in DockerFrontend buildNext.js imageGHCRAPI = worker = beatSSH deploypull · compose upDigitalOceansingle-host ComposeMigrate + reloadalembic · nginx
  1. Five layers in one codebase. Workers run the same services as the API. PostgreSQL is the source of truth, and the queue only carries messages.
  2. The browser reaches Nginx, which terminates TLS, sets CSP and forwards /api/* to FastAPI.
  3. Middleware assigns a trace id, audits the request, applies rate limits and records metrics.
  4. Application services hold the logic: discovery, ranking, agents, knowledge and the assistant.
  5. Celery Beat schedules work and RabbitMQ carries it to workers that use the same image.
  6. PostgreSQL with pgvector stores records, vectors, job state and the outbox. Raw files sit on a volume.
  7. Every push to main runs tests, publishes images and deploys to a single DigitalOcean host.

FIG 02 — System architecture. Pick a path to trace one journey; open full view to zoom.

04 — Techniques

What each stage does, and its settings

The retrieval pipeline below is the version the evaluation measures. Every setting here was either set by an eval run or is listed as a known limitation.

Retrieval-augmented answers

Extraction
Format-specific parsers in an isolated subprocess: PyMuPDF, BeautifulSoup/lxml, DOCX, Markdown. Normalization keeps section paths, pages and exact character offsets, so citations can point back into the source.
size, page, block,
timeout + memory limits
Chunking
Structure-aware, lossless spans. Splits at headings first, then paragraph, sentence and word. Every chunk is an exact slice of the canonical text.
2048 B chunks · 256 B overlap
128 B minimum · UTF-8 bytes
Embedding
Validated vectors. Each vector is checked for dimension, finite values and a non-zero norm before it's stored. The configuration is hashed and immutable, so changing any setting means a new index.
text-embedding-3-small
1536 dims · batches ≤ 64
Retrieval
Hybrid search in a single SQL statement: pgvector cosine plus Postgres full-text, fused with Reciprocal Rank Fusion. Only ranks count, so the two score scales never have to be calibrated against each other.
RRF k = 60 · equal weights
exact scan · owner-scoped
Routing
An LLM classifier returns an intent (feed, knowledge, both, profile, off-topic, unsafe) and rewrites follow-ups so they stand alone. Speculative retrieval starts both searches while the router runs.
20 s timeout
fails open to "both"
Context
Rank-order selection with overlap and duplicate removal. Each excerpt is binary-searched to the longest prefix that still fits the rendered prompt.
12 excerpts · 24 KiB window
no per-document cap
Generation
Streamed over Server-Sent Events with an [E#] citation in every paragraph, at temperature 0. A small gate holds back the first characters so the INSUFFICIENT_EVIDENCE marker never flashes on screen.
status · delta · reset
done · error events
Persistence
Citation snapshots store the cited text, the document version and canonical offsets. Citations stay valid after the index is rebuilt.
saved before the
done event

How an answer earns its citations

Each check is cheaper than the next. Most answers pass at the first step.

  1. Structural validationEvery paragraph cites a real E#. No URLs, and no other brackets.
  2. Deterministic attributionAn uncited paragraph is matched by title quote or ≥ 30% word overlap with a 2× lead. No LLM call.
  3. One LLM repairRegenerates with the failing paragraphs named by position, never quoted. The UI gets a reset event.
  4. Support checkgpt-4.1-mini sees the question and the evidence but not the answer, and must quote the supporting sentence.
  5. Identifier guardVersions, years and variants such as X3/X4, v2 and 2024 must match exactly. A sibling's figure doesn't count.
  6. AbstainIf no grounded answer survives, the assistant says the sources don't cover it. It never errors.

Feed ranking

Interests now dominate the score. The old weights let credibility and freshness fill the feed with off-topic items.

Current weightssince Oct 6
relevance 601012108
Original weightsJun – Oct 5
relevance 4020151510
RelevanceCredibility · Freshness · Novelty · Feedback
Relevance calibration: cosine similarity below 0.25 maps to 0, 0.50 and above maps to 1. Unrelated control interests never exceeded 0.15; on-topic items scored 0.37 to 0.57.unrelated ≤ 0.15AI feed≈ 0.25on-topic 0.37 – 0.570.1.2.3.4.5.60.51cosine similarity, interest ↔ item

Calibrated on 206 live items. Items below 0.15 relevance keep only half their score.

Discovery that fills its own gaps

Coverage gaps
After the curated sources, CoverageGapFiller counts fresh items that match each interest. It searches the open web only for interests below the threshold.
few gaps per run · ≤ 2 per site
shared query log with TTL
Source lifecycle
Sites found by search join as low-trust candidates. Every day they are promoted (their RSS feed is found and scanned hourly) or retired, based on how readable they are and the feedback their items get.
daily job
admin approve / block
Dedupe + budget
Deduplicates by canonical URL and normalized headline, so syndicated stories are stored once. Only the best ~20 candidates are processed, inside a two-week news window.
per-user content pool
hard relevance floor
Resilience
Provider fallback with circuit breakers. A transient failure moves the call to the other LLM. A stream falls back only before its first token reaches the reader.
connect 5 s · read 60 s
3 fails → skip 30 s

05 — Engineering decisions

The calls that shaped the system

1

Keep one modular monolith

Context
One engineer. Discovery, ranking, agents and RAG share users, content and embeddings.
Decision
FastAPI layers (routes → services → domain → infrastructure), with Celery workers running the same codebase from the same image.
Result
One deploy, one migration chain, and the same code path for user-started and scheduled runs. Splitting into services is left for when a real scaling seam appears.
2

PostgreSQL is the source of truth, including for jobs

Context
Ingestion must survive worker restarts, duplicate deliveries and a broker that loses messages.
Decision
A transactional outbox (knowledge_dispatches) and database leases with fencing tokens. A maintenance task republishes due work every 15 seconds.
Result
At-least-once delivery, made safe because stale workers can't commit. A crash resumes from the last checkpoint: raw bytes and canonical versions are never redone.
3

Evidence is immutable, indexes are disposable

Context
Chunk size, embedding model and retrieval will all change. Old citations must still resolve afterwards.
Decision
Raw bytes and canonical document versions are permanent. Chunks and vectors are derived per configuration. Citations snapshot their text and offsets.
Result
A new index builds alongside the live one, passes coverage and smoke checks, then activates atomically. The previous configuration can be reactivated.
4

pgvector instead of a vector database

Context
Retrieval must filter by owner, version, index build and date in the same query.
Decision
Embeddings live next to the relational data. Hybrid search is one SQL statement with RRF.
Result
Ownership is enforced in SQL, with nothing to sync and no second store to back up. It uses an exact scan, which is a trade-off (06).
5

Persist the reason with every decision

Context
Readers and I both need to know why an item ranked, or why an agent changed a preference.
Decision
A RecommendationTrace per recommendation (factor scores, weights, matched interests) and an AdaptationEvent per agent change (reason, confidence, before/after).
Result
"Why this recommendation?" reads stored data instead of regenerating an explanation. Explicit interests are kept separate from learned preferences, so adaptation never overwrites what the reader said.
6

Stream answers, then validate, then commit

Context
A wait of about 3 seconds feels slow, but a cited answer can't be checked until it is complete.
Decision
Server-Sent Events stream provisional text. Validation runs on the full answer. A failed check sends reset and a repaired answer follows. The turn is saved before done.
Result
Text appears quickly and only validated answers are saved. Nginx serves the route unbuffered.
7

Observability is part of the application

Context
A Discover journey crosses the API, workers, LLMs, embeddings and email.
Decision
Trace IDs in middleware, and a W3C traceparent saved on knowledge jobs so the trace continues across the outbox. Each service exports Prometheus metrics.
Result
One Discover run shows as one trace in Grafana, alongside Jaeger's service map. Grafana UI edits are saved back to the repo.

06 — Trade-offs

What I gave up, and when I'd change it

ChoseOverCost acceptedRevisit when
Support check before every answerTrusting citation structureAbout 6–7% false abstention on answerable questions, plus an extra model callA semantic near-miss detector beats it on a held-out set
Exact cosine scanHNSW / IVFFlat indexLinear cost per query as a library growsPersonal libraries reach tens of thousands of chunks
Byte-based token budgetsModel tokenizersThe window is conservative, about 4 bytes per tokenMultiple providers need exact per-model budgets
gpt-4.1-mini as judgegpt-4.11–4 points stricter on correctness. Only numbers from the same judge are comparedNever mixed. Every run was re-judged after the switch
One global active indexPer-user index versionsA re-index migrates every library togetherUsers need different embedding models
Single-host ComposeKubernetes, managed servicesRate limits and caches are process-local, and storage is a shared volumeA second API replica is needed (move to Redis and object storage)
Rank-only fusion, no rerankerScore fusion, cross-encoderA strong single-channel match carries no extra weightHit@10 is already 97.3%, so answer quality is the bottleneck, not recall

07 — Evaluation

Measured before it shipped

RAG quality was measured on a fixed corpus in an isolated stack. The corpus is 97 Wikipedia articles across nine AI topics plus 13 fictional documents about products and organizations that exist nowhere else. Questions about them can only be answered from retrieval, never from what the model already knows. The fictional documents include near-duplicate traps such as Petrel X3 and X4, Quillnet v1 and v2, and Marlowe-7 base and instruct.

143

Golden questions · 73 answerable, 70 not

97.3%

Retrieval Hit@10 · MRR 0.795

97.1%

Best correct abstention, knowledge chat

0

Production errors per run, down from 4–5

What a golden case looks like

rag-045 · distractorANSWERED

What is the maximum flight time of the Petrel X3?

31 minutes with no payload E1

Trap: the Petrel X4 field manual says 38 minutes. That figure is listed as a forbidden fact.

rag-086 · unanswerableMUST ABSTAIN

What is the Petrel X4 Pro's return-to-home altitude?

My sources don't cover the X4 Pro. They give figures for the X4 only.

At v1.0 the system answered with the X4's 60 m and the support check accepted it. The identifier guard was built to catch this.

Correct abstention across release candidates

Each bar spans two independent runs. A gate passes only if it passes in both. Each release added freshly written unanswerable questions, frozen before that release's fixes were designed.

Knowledge chatAsk DeepFeed assistant95% release gate
Correct abstention. v1.0: knowledge 86.7 to 90.0 percent, assistant 66.7 to 76.7. v1.1: both 94.0. v1.2: knowledge 95.7 to 97.1, assistant 94.3 to 95.7. Gate 95 percent.gate 95%v1.0golden-v2.1 · 3086.7–90.066.7–76.7v1.1golden-v3 · 5094.094.0v1.2golden-v4 · 7095.7–97.194.3–95.760%70%80%90%100%

FIG 03 — Correct abstention per release candidate, two runs each

Release gates, v1.2

GateThresholdRun 1Run 2Result
Retrieval Hit@10 / Recall@10 / MRR@10≥ 90% / 85% / 0.7097.3 / 96.6 / 0.795samePASS
Knowledge: correct abstention (70)≥ 95%95.7%97.1%PASS
Knowledge: citations resolve / on expected doc100% / ≥ 95%100 / 100%100 / 99.2%PASS
Knowledge: unsupported claims (judge)≤ 5%4.0%3.3%PASS
Assistant: correct abstention (70)≥ 95%94.3%95.7%EXCEPTION
Assistant: citations resolve / on expected doc100% / ≥ 95%100 / 97.0%100 / 96.4%PASS
Assistant: unsupported claims (judge)≤ 5%4.0%2.8%PASS
Evaluation crashes / production errors00 / 00 / 0PASS

Documented release exception

The assistant missed the abstention gate by a single question in one run (66 of 70, where 67 were needed). I shipped v1.2 with that exception written down rather than tuning on the test set until it passed. The remaining misses are sibling-item answers that a token rule can't catch:

  • a time window stated in words ("before the policy took effect")
  • a component of a named product (the Petrel X3's battery, not the aircraft)
  • a variant name with no digit ("Quillnet-Lite")

The tuning runs that set the defaults

RunChangeJudged correctUnsupported claims
v0.1Baseline: round-robin context across documents67.1%14.4%
v0.2aContext in retrieval rank order. Context recall went from 74.7% to 92.5%86.3%4.0%
v0.2b24 KiB context window87.7%6.6%
v0.2c24 KiB, no per-document cap. Adopted as the default91.8%3.2%
v0.2d32 KiB with a cap of 4 per document. Rejected84.9%5.3%

Knowledge chat, answerable cases, judged by gpt-4.1-mini. Most of the v0.1 "padding from prior knowledge" disappeared once the model was given the passage that answered the question.

Method

Deterministic metrics first

Retrieval is scored from chunk-independent evidence quotes, with no LLM needed.

A calibrated judge

gpt-4.1-mini agreed with gpt-4.1 on 96.8% of verdicts. It was adopted for cost, with its known 1–4 point offset recorded.

Fresh held-out sets

golden-v3 and golden-v4 each added 20 unanswerable questions, frozen before that round's fixes.

A separate tuning set

Changes were developed against it, so no test case was used to tune.

Two runs per release candidate

A gate passes only when both runs pass.

A regression baseline

evaluation.compare flags any gate a candidate breaks relative to v1.2.

08 — Story of the product

Five months, from a scaffold to a measured release

Jun 8

First full-stack commit

FastAPI, Celery, pgvector and Next.js, with the agents written as services from the start. It ran, but most of it had never been exercised end to end.

Aug 27

Discover Now works end to end

The first real run showed Celery tasks routed to queues no worker consumed. I registered and routed them properly, bounded task runtimes, and made orphaned runs heal themselves after a worker restart.

Sep 4–5

CI/CD, and making the tests honest

Images went to GHCR with automatic deploys. Getting the backend tests green meant fixing five separate real bugs, not skipping tests. Every service got real Prometheus metrics.

Sep 14–15

The knowledge library

Built in eleven planned phases: permanent storage, extraction, chunking, embeddings, durable ingestion, hybrid retrieval, context budgeting, grounded chat, safe reindexing, related documents and the UI. DeepFeed stopped being only a feed.

Oct 4–5

Production hardening

Dependency and runtime upgrades were validated in Docker. Auth moved to in-memory access tokens with an HttpOnly rotating refresh cookie. Nginx gained TLS, CSP and edge limits.

Oct 6

The typo that rewrote ranking

A user who followed Rainforcement Learning saw about 0% relevance on every item. Relevance was a substring match, and 60% of the score ignored interests entirely. I replaced it with calibrated semantic relevance, gave interests 60% of the score and added a relevance floor. The same day shipped the assistant with memory, plus email verification.

Oct 8–9

Streaming, and staying up

Answers began streaming over SSE. Speculative retrieval cut the wait for the router. Provider fallback and circuit breakers keep the assistant answering through an outage.

Oct 9–12

The evaluation program

I built the corpus, golden sets and a calibrated judge, then ran tuning sweeps. v1.0 was blocked on abstention: in its worse run, the assistant answered a third of the unanswerable questions. v1.1 got to 94%. v1.2 shipped, with the remaining gap documented as an exception.

Oct 13

Seeing the whole journey

Distributed tracing with Jaeger and Grafana gives one trace per Discover run, carried across the outbox. Per-user content pools stopped one reader's search results from filling another reader's feed.

Oct 15

A face that matches the brand

I redesigned the UI around the logo's palette and reading-room typography, and moved deployment to a DigitalOcean droplet.

09 — What's next

The next release, already scoped