Skip to content

Commit 38802fa

Browse files
Merge pull request #5 from amantebriwal4321/feat/reliability-and-tests
Feat/reliability and tests
2 parents 6c77062 + cd243d1 commit 38802fa

15 files changed

Lines changed: 715 additions & 47 deletions

File tree

‎.github/workflows/backend.yml‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,12 @@ jobs:
99
with:
1010
python-version: '3.11'
1111
- name: Install dependencies
12-
run: pip install -r backend/requirements.txt
12+
run: pip install -r backend/requirements-dev.txt
13+
- name: Run tests
14+
# Throwaway SQLite DB, no API keys, no network - see tests/conftest.py.
15+
run: cd backend && python -m pytest tests -q
1316
- name: Check imports
1417
run: cd backend && python -c "from app.main import app; print('✅ App imports successfully')"
15-
- name: Verify API routes
16-
run: |
17-
cd backend
18-
python -c "
19-
from app.main import app
20-
routes = [r.path for r in app.routes]
21-
assert '/api/v1/tools' in routes or any('/tools' in r for r in routes), 'Missing /tools route'
22-
print(f'✅ {len(routes)} routes registered')
23-
"
2418

2519
docker-build:
2620
needs: lint-and-build

‎CLAUDE.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,13 @@ alembic revision --autogenerate -m "message"
4646
alembic upgrade head
4747
```
4848

49-
There is **no test suite** in this repo yet.
49+
### Tests
50+
```bash
51+
cd backend
52+
pip install -r requirements-dev.txt # requirements.txt + pytest
53+
python -m pytest tests -q # ~85 tests, ~1.5s
54+
```
55+
`tests/conftest.py` points `DATABASE_URL` at a **throwaway SQLite file** (never `backend/test.db`), blanks every API key, and sets `RUN_SCRAPER_INLINE=0` + `WARM_RESOURCE_CACHE=0`, all before `app` is imported — so the suite needs no database, secrets or network and gives the same answer in CI as locally. Backend CI (`.github/workflows/backend.yml`) runs it on every push/PR. Coverage today: the project video gate + cache key (`test_projects.py`, with the real titles that reached production as regressions), data freshness (`test_health.py`), the scheduler's success stamping (`test_scheduler.py`), the score's contract (`test_scoring.py`), and the booted app (`test_api.py`). Pure logic belongs in a service module where it can be tested without a request — `projects.video_cache_slug` was moved out of the endpoint for exactly that reason.
5056

5157
## Architecture
5258

@@ -56,10 +62,10 @@ scraper.py → scoring.py → models (Tool/ToolSnapshot) → mvp.py API
5662
(sources) (0–100 %ile) (DB + time series) (/api/v1/*) (typed fetch layer) (UI)
5763
```
5864

59-
1. **`app/services/scheduler.py`** — `run_scraper_loop()` runs every 30 min (started as an asyncio task at app startup). `perform_full_scrape()` is an 8-step pipeline: sync tool registry → fetch community sources → sentiment → GitHub repo stats → score → persist snapshots → update tools → recompute. Live progress is exposed via `GET /api/v1/status`.
65+
1. **`app/services/scheduler.py`** — `run_scraper_loop()` runs every 30 min (started as an asyncio task at app startup). `perform_full_scrape()` is an 8-step pipeline: sync tool registry → fetch community sources → sentiment → GitHub repo stats → score → persist snapshots → update tools → recompute. Live progress is exposed via `GET /api/v1/status`. `perform_full_scrape` never raises (the loop must survive) but **returns True only when the final commit landed**; the loop stamps `last_scraped_time` on success alone and otherwise increments `consecutive_failures`. It used to stamp unconditionally, so a crashed pipeline was reported as a fresh scrape and the site said "Live".
6066
2. **`app/services/scraper.py`** — async fetchers: `fetch_github_repo_stats` (targeted per-repo, ETag caching + adaptive rate limiting), `fetch_hackernews`, `fetch_devto`, `fetch_reddit` (RSS, no auth), `fetch_tech_news` (RSS). `batch_sentiment_analysis` uses Groq (`llama-3.1-8b-instant`) — a no-op/skip when `GROQ_API_KEY` is empty.
61-
3. **`app/services/scoring.py`** — `calculate_all_tool_scores` normalizes weighted mentions + GitHub signals into **percentile ranks (0–100)** across all tools at once (this is why scores are relative, not absolute). Also classifies growth stage, trend, learning priority, and generates recommendation text.
62-
4. **`app/api/endpoints/mvp.py`** — the single router, mounted at `settings.API_V1_STR` (`/api/v1`). All endpoints live here: `/tools`, `/tools/{slug}`, `/tools/{slug}/history`, `/tools/{slug}/resources` (learning videos + platforms, see below), `/tools/compare`, `/tools/by-domain`, `/domains`, `/domains/{slug}/learning-path`, `/roadmaps`, `/roadmaps/{slug}` (steps hydrated with per-step tools + each tool's top video), `/progress/{summary,/{slug},toggle}` (learning progress, auth-gated), `/notifications/{subscribe,status,unsubscribe}` (daily-nudge opt-in), `/overview`, `/status`, `/health`, `/ready`, `/admin/scrape` + `/admin/send-daily-digests` (gated by `ADMIN_API_KEY`).
67+
3. **`app/services/scoring.py`** — `calculate_all_tool_scores` scores each tool on an **absolute 0–100 scale** from its own signals only: floor-anchored log stars (60%) and forks (15%) plus community mentions saturating at 25 (25%). A tool's score does not move when an unrelated tool moves — `test_scoring.py` pins this. (This file used to say percentile ranks; `_percentile_rank` is unused.) Also classifies growth stage, trend, learning priority, and generates recommendation text.
68+
4. **`app/api/endpoints/mvp.py`** — the single router, mounted at `settings.API_V1_STR` (`/api/v1`). All endpoints live here: `/tools`, `/tools/{slug}`, `/tools/{slug}/history`, `/tools/{slug}/resources` (learning videos + platforms, see below), `/tools/compare`, `/tools/by-domain`, `/domains`, `/domains/{slug}/learning-path`, `/roadmaps`, `/roadmaps/{slug}` (steps hydrated with per-step tools + each tool's top video), `/progress/{summary,/{slug},toggle}` (learning progress, auth-gated), `/notifications/{subscribe,status,unsubscribe}` (daily-nudge opt-in), `/overview`, `/status`, `/health` (always 200; `status` is ok/degraded/error with a `data` freshness report), `/health/data` (**503 when data is stale >2h, the scraper has failed 2+ cycles running, or nothing was ever scraped — point an uptime monitor here**; logic in `app/services/health.py:assess_freshness`), `/ready`, `/admin/scrape` + `/admin/send-daily-digests` (gated by `ADMIN_API_KEY`).
6369
5. **`app/models/all_models.py`** — tables: `Domain`, `Tool` (now also carries `homepage`/`latest_version`/`latest_release_at` for the resource docs-link + stale-tutorial warning), `ToolSnapshot` (time series, incl. `stars`), `ToolRoadmap`, `UserProgress` (completed roadmap steps per user), `ToolResource` (cached learning videos/platforms), `NotificationPref` (daily-nudge opt-in). Roadmaps are keyed by **domain slug**. New model fields are reconciled onto existing DBs at startup by `app/db/migrate.py:ensure_columns` (additive `ALTER TABLE ADD COLUMN` only — `create_all` never adds columns to an existing table).
6470

6571
### Learning layer (the retention + growth product)
@@ -118,7 +124,7 @@ To grow the signal further: add more subreddits/RSS feeds, fetch HN story text (
118124
- The app runs fine with **empty `GITHUB_TOKEN`/`GROQ_API_KEY`** (degraded: no GitHub stats, no sentiment) — don't make either a hard requirement to boot.
119125

120126
## Environment variables
121-
Backend (`backend/.env`): `GITHUB_TOKEN`, `GROQ_API_KEY`, `YOUTUBE_API_KEY` (optional — enables ranked video results on `/tools/{slug}/resources`; without it the endpoint returns curated platform links and reports `videos_live: false`), `CLERK_PUBLISHABLE_KEY` (optional but required in production — the same public `pk_...` value as the frontend; when set, `/progress` verifies the Clerk session token server-side via `app/core/auth.py` and ignores any client-supplied `user_id`; when empty it falls back to a client id for local dev), `RESEND_API_KEY` + `DIGEST_FROM` + `SITE_URL` (optional — the daily learning-nudge email; empty → the `/admin/send-daily-digests` batch runs as a safe no-op and sends nothing; trigger it from an external daily cron with the `X-Admin-Key` header), `ADMIN_API_KEY` (optional), `DATABASE_URL` (auto-set by Docker; empty → SQLite). Frontend (`frontend/.env.local`): `BACKEND_ORIGIN` (where the Next server proxies `/api/v1/*` — **read at build time**; local `http://localhost:8000`, docker-compose `http://backend:8000`, prod = the public backend URL), `NEXT_PUBLIC_SITE_URL` (absolute site URL for OG/canonical/sitemap; single source `src/lib/site.ts`), `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`, `CLERK_SECRET_KEY`. (`NEXT_PUBLIC_API_URL` was removed in favour of the proxy.)
127+
Backend (`backend/.env`): `GITHUB_TOKEN`, `GROQ_API_KEY`, `YOUTUBE_API_KEY` (optional — enables ranked video results on `/tools/{slug}/resources`; without it the endpoint returns curated platform links and reports `videos_live: false`), `CLERK_PUBLISHABLE_KEY` (optional but required in production — the same public `pk_...` value as the frontend; when set, `/progress` verifies the Clerk session token server-side via `app/core/auth.py` and ignores any client-supplied `user_id`; when empty it falls back to a client id for local dev), `RESEND_API_KEY` + `DIGEST_FROM` + `SITE_URL` (optional — the daily learning-nudge email; empty → the `/admin/send-daily-digests` batch runs as a safe no-op and sends nothing; trigger it from an external daily cron with the `X-Admin-Key` header), `ADMIN_API_KEY` (optional), `WARM_RESOURCE_CACHE` (default `1`; `0` skips the startup video-cache warm — the test suite sets it), `DATABASE_URL` (auto-set by Docker; empty → SQLite). Frontend (`frontend/.env.local`): `BACKEND_ORIGIN` (where the Next server proxies `/api/v1/*` — **read at build time**; local `http://localhost:8000`, docker-compose `http://backend:8000`, prod = the public backend URL), `NEXT_PUBLIC_SITE_URL` (absolute site URL for OG/canonical/sitemap; single source `src/lib/site.ts`), `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`, `CLERK_SECRET_KEY`. (`NEXT_PUBLIC_API_URL` was removed in favour of the proxy.)
122128

123129
## Deployment
124130
Live (beta): **frontend on Vercel** (root `frontend`), **backend + Postgres on Render + Neon** (root `backend`, Docker). The same-origin proxy means Vercel forwards `/api/v1/*` to the Render backend — no CORS to configure. Full step-by-step (env-var tables, Clerk/scraper/cron notes, single-VPS docker-compose alternative) is in **`DEPLOY.md`**. Set `BACKEND_ORIGIN` in Vercel *before* the first build (it's baked into the rewrite), and `NEXT_PUBLIC_SITE_URL` to the real domain. The Render free tier sleeps on inactivity (~50s cold start on the first request) — expected for the beta.

‎backend/app/api/endpoints/mvp.py‎

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
from fastapi import APIRouter, Depends, HTTPException, Query, Header, Request
2626
from sqlalchemy.orm import Session
2727
from sqlalchemy import func
28-
import hashlib
2928
from datetime import date, timedelta, datetime, timezone
3029
from app.db.session import get_db
3130
from app.core.config import settings
@@ -34,6 +33,7 @@
3433
from app.services.scoring import calculate_star_velocity
3534
from app.services import resources as resources_svc
3635
from app.services import projects as projects_svc
36+
from app.services import health as health_svc
3737
from app.core.cache import get_cached, set_cached
3838
from app.core.auth import verified_clerk_user
3939

@@ -638,14 +638,7 @@ async def _verified_walkthrough(project: dict, db: Session) -> dict:
638638
# then has to re-fetch instead of serving the old query's winner for
639639
# up to 24h — which is exactly the trap that hid two generic results
640640
# behind a correct-looking fix.
641-
w = project["walkthrough"]
642-
qhash = hashlib.sha1(
643-
repr((
644-
search, w.get("must"), w.get("any"), w.get("deny"),
645-
projects_svc.GATE_VERSION,
646-
)).encode()
647-
).hexdigest()[:8]
648-
cache_slug = f"project:{project['slug']}:{qhash}"
641+
cache_slug = projects_svc.video_cache_slug(project)
649642
cached = (
650643
db.query(ToolResource)
651644
.filter(ToolResource.tool_slug == cache_slug)
@@ -1406,32 +1399,62 @@ def get_scraper_status():
14061399
}
14071400

14081401

1402+
def _freshness(db: Session) -> dict:
1403+
last_snapshot = db.query(ToolSnapshot).order_by(ToolSnapshot.recorded_at.desc()).first()
1404+
return health_svc.assess_freshness(
1405+
scrape_status.get("last_scraped_time"),
1406+
last_snapshot.recorded_at if last_snapshot else None,
1407+
scrape_status.get("consecutive_failures", 0),
1408+
)
1409+
1410+
14091411
@router.get("/health")
14101412
def health_check(db: Session = Depends(get_db)):
1411-
"""Production health check — verifies DB connectivity and data freshness."""
1413+
"""Liveness plus an honest report on the data.
1414+
1415+
Always 200, because a platform health check restarting the process over
1416+
stale data would not fix the data. The status field is no longer a constant:
1417+
it used to read "ok" even with the database unreachable.
1418+
"""
14121419
from sqlalchemy import text
14131420
try:
14141421
db.execute(text("SELECT 1"))
14151422
db_status = "connected"
14161423
except Exception:
14171424
db_status = "error"
14181425

1419-
last_snapshot = db.query(ToolSnapshot)\
1420-
.order_by(ToolSnapshot.recorded_at.desc())\
1421-
.first()
1422-
1423-
tool_count = db.query(Tool).count()
1426+
freshness = _freshness(db) if db_status == "connected" else None
1427+
if db_status != "connected":
1428+
status = "error"
1429+
elif not freshness["healthy"]:
1430+
status = "degraded"
1431+
else:
1432+
status = "ok"
14241433

14251434
return {
1426-
"status": "ok",
1435+
"status": status,
14271436
"db": db_status,
1428-
"tools_tracked": tool_count,
1429-
"last_scrape": last_snapshot.recorded_at.isoformat() if last_snapshot else None,
1437+
"tools_tracked": db.query(Tool).count() if db_status == "connected" else None,
1438+
"last_scrape": freshness["last_success"] if freshness else None,
1439+
"data": freshness,
14301440
"is_scraping": scrape_status.get("is_running", False),
14311441
"version": "1.0.0",
14321442
}
14331443

14341444

1445+
@router.get("/health/data")
1446+
def data_health(db: Session = Depends(get_db)):
1447+
"""503 when the numbers on the site are not current. Point an uptime monitor here.
1448+
1449+
This is the alert /health deliberately is not: it fails on stale data, on
1450+
a scraper failing repeatedly, and on a database that has never been scraped.
1451+
"""
1452+
freshness = _freshness(db)
1453+
if not freshness["healthy"]:
1454+
raise HTTPException(status_code=503, detail=freshness)
1455+
return freshness
1456+
1457+
14351458
@router.get("/ready")
14361459
def readiness_check(db: Session = Depends(get_db)):
14371460
"""Kubernetes readiness probe — returns 503 until enough tools are seeded."""

‎backend/app/main.py‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
from fastapi import FastAPI, Request, Response
2-
from fastapi.middleware.cors import CORSMiddleware
3-
from app.core.config import settings
41
import asyncio
5-
import sys
2+
import logging
63
import os
4+
import sys
5+
6+
from fastapi import FastAPI, Request, Response
7+
from fastapi.middleware.cors import CORSMiddleware
78

89
# ━━━ Loguru Setup (TASK-011) ━━━
910
from loguru import logger
10-
import logging
11+
12+
from app.core.config import settings
1113

1214
# Remove default loguru handler and re-add with our format
1315
logger.remove()
@@ -56,8 +58,8 @@ def emit(self, record: logging.LogRecord) -> None:
5658

5759
# ━━━ Rate Limiting (TASK-009) ━━━
5860
from slowapi import Limiter, _rate_limit_exceeded_handler
59-
from slowapi.util import get_remote_address
6061
from slowapi.errors import RateLimitExceeded
62+
from slowapi.util import get_remote_address
6163

6264
limiter = Limiter(key_func=get_remote_address)
6365

@@ -100,7 +102,7 @@ async def startup_event():
100102

101103
# Seed database with tools, domains, and roadmaps if empty
102104
from app.db.session import SessionLocal
103-
from app.services.seed import run_seed, reconcile_catalog
105+
from app.services.seed import reconcile_catalog, run_seed
104106
db = SessionLocal()
105107
try:
106108
run_seed(db)
@@ -117,8 +119,11 @@ async def startup_event():
117119
# Warm the learning-resource cache in the background so roadmap steps and
118120
# tool pages show real video titles/thumbnails on first visit, not just a
119121
# URL. Non-blocking — startup returns immediately.
120-
from app.services.resources import warm_resource_cache, CURATED_VIDEOS
121-
asyncio.create_task(warm_resource_cache(SessionLocal, list(CURATED_VIDEOS.keys())))
122+
# WARM_RESOURCE_CACHE=0 skips it, for the test suite, which must not reach
123+
# YouTube from a CI runner.
124+
if os.getenv("WARM_RESOURCE_CACHE", "1") == "1":
125+
from app.services.resources import CURATED_VIDEOS, warm_resource_cache
126+
asyncio.create_task(warm_resource_cache(SessionLocal, list(CURATED_VIDEOS.keys())))
122127

123128

124129
# ━━━ CORS ━━━

‎backend/app/services/health.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""Data-freshness assessment, kept pure so it can be tested without a server.
2+
3+
The API's job here is to say, truthfully, whether the numbers on the site are
4+
current. That used to be impossible to get wrong-looking: /health returned
5+
"status": "ok" unconditionally, even with the database unreachable, and nothing
6+
reported a scraper that had stopped producing data.
7+
"""
8+
from __future__ import annotations
9+
10+
from datetime import datetime, timedelta, timezone
11+
from typing import Any
12+
13+
# Four missed 30-minute cycles. Long enough to ride out one slow run or a
14+
# free-tier cold start, short enough that a dead scraper is noticed same-day.
15+
STALE_AFTER = timedelta(hours=2)
16+
17+
# Consecutive failed cycles before the scraper is called failing even though
18+
# the last good data is still inside the freshness window.
19+
FAILING_AFTER = 2
20+
21+
22+
def _parse(ts: Any) -> datetime | None:
23+
if ts is None:
24+
return None
25+
if isinstance(ts, datetime):
26+
dt = ts
27+
else:
28+
try:
29+
dt = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
30+
except ValueError:
31+
return None
32+
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
33+
34+
35+
def assess_freshness(
36+
last_success: Any,
37+
last_snapshot: Any = None,
38+
consecutive_failures: int = 0,
39+
now: datetime | None = None,
40+
stale_after: timedelta = STALE_AFTER,
41+
) -> dict[str, Any]:
42+
"""Classify the data as fresh, stale, failing or never.
43+
44+
`last_success` is the in-process scrape stamp; `last_snapshot` is the newest
45+
persisted ToolSnapshot. The snapshot is the fallback because the in-process
46+
stamp resets on every restart - and on a sleeping free tier that is often.
47+
"""
48+
now = now or datetime.now(timezone.utc)
49+
last = _parse(last_success) or _parse(last_snapshot)
50+
51+
if last is None:
52+
return {"state": "never", "healthy": False, "last_success": None,
53+
"age_minutes": None, "consecutive_failures": consecutive_failures}
54+
55+
age = now - last
56+
if age > stale_after:
57+
state = "stale"
58+
elif consecutive_failures >= FAILING_AFTER:
59+
state = "failing"
60+
else:
61+
state = "fresh"
62+
63+
return {
64+
"state": state,
65+
"healthy": state == "fresh",
66+
"last_success": last.isoformat(),
67+
"age_minutes": max(0, int(age.total_seconds() // 60)),
68+
"consecutive_failures": consecutive_failures,
69+
"stale_after_minutes": int(stale_after.total_seconds() // 60),
70+
}

‎backend/app/services/projects.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040

4141
from __future__ import annotations
4242

43+
import hashlib
4344
import re
4445
from typing import Any
4546

@@ -773,6 +774,21 @@ def list_projects(
773774
NEGATED = "(?:^|[^a-z])(?:no|not|without|instead of)[^a-z][^.,;:!?]{0,24}?%s"
774775

775776

777+
def video_cache_slug(project: dict[str, Any]) -> str:
778+
"""ToolResource key for a project's chosen walkthrough video.
779+
780+
The cached winner depends on the query, all three gate fields and the gate's
781+
logic, so the key hashes every one of them. Each omission already shipped
782+
once as a fix that looked like it changed nothing for 24 hours: the search
783+
string, then `deny`, then the matching logic itself (hence GATE_VERSION).
784+
"""
785+
w = project.get("walkthrough") or {}
786+
digest = hashlib.sha1(
787+
repr((w.get("search"), w.get("must"), w.get("any"), w.get("deny"), GATE_VERSION)).encode()
788+
).hexdigest()[:8]
789+
return f"project:{project['slug']}:{digest}"
790+
791+
776792
def video_matches(title: str, walkthrough: dict[str, Any]) -> bool:
777793
"""Does this video's REAL title match what the project is about?
778794

0 commit comments

Comments
 (0)