diff --git a/README.md b/README.md index fedd3fb..6fc32fd 100644 --- a/README.md +++ b/README.md @@ -401,7 +401,7 @@ after a prompt change only pays for what changed. ## Deployment -- **Backend**: `backend/render.yaml` is a single Render Blueprint web service (no separate bot or worker), driven by webhook pushes and cron pings so it fits Render's free tier. It runs `alembic upgrade head` on start and generates `TRACKING_SIGNING_SECRET`. Set `GEMINI_MODEL=gemini-3.5-flash-lite` and `APP_TIMEZONE`. Steps: [SETUP.md](SETUP.md) §8. +- **Backend**: `backend/render.yaml` is a single Render Blueprint web service (no separate bot or worker), driven by webhook pushes and cron pings so it fits Render's free tier. It runs `alembic upgrade head` on start (a database created by v1, which has tables but no migration history, is upgraded in place and keeps its data) and generates `TRACKING_SIGNING_SECRET`. Set `GEMINI_MODEL=gemini-3.5-flash-lite` and `APP_TIMEZONE`. Steps: [SETUP.md](SETUP.md) §8. - **Dashboard**: Next.js on Vercel. Set `NEXT_PUBLIC_BACKEND_URL`, `AUTH_SECRET`, `AUTH_GOOGLE_ID`/`AUTH_GOOGLE_SECRET` and `INTERNAL_AUTH_SECRET` (must match the backend's) before the first deploy, and set **Root Directory** to `dashboard`. Steps: [SETUP.md](SETUP.md) §9. - **Google OAuth**: add the production Vercel URL as an authorized origin and redirect URI, or sign-in fails with `redirect_uri_mismatch`. Steps: [SETUP.md](SETUP.md) §10. - After both are deployed, register the webhook and both cron triggers: [SETUP.md](SETUP.md) §5–7. diff --git a/backend/app/personalization.py b/backend/app/personalization.py index 4b4ef06..b136943 100644 --- a/backend/app/personalization.py +++ b/backend/app/personalization.py @@ -20,6 +20,7 @@ """ import datetime as dt +import logging from dataclasses import dataclass import numpy as np @@ -39,6 +40,8 @@ User, ) +logger = logging.getLogger("loopwire.personalization") + SIGNAL_WEIGHTS = { EVENT_FEEDBACK_UP: 2.0, EVENT_CLICKED_SOURCE: 1.0, @@ -118,7 +121,13 @@ def profile_embedding(db: Session, user: User) -> list[float] | None: if not user.interest_profile_text: return None if user.interest_profile_embedding is None: - user.interest_profile_embedding = compute_embedding(user.interest_profile_text) + try: + user.interest_profile_embedding = compute_embedding(user.interest_profile_text) + except Exception: + # A failed embedding call (quota, outage) must not cost the user their + # dispatch: rank without the written profile and retry next time. + logger.exception("Profile embedding failed for user #%s - ranking without it", user.id) + return None return user.interest_profile_embedding diff --git a/backend/migrations/versions/28379ab37e18_v2_schema.py b/backend/migrations/versions/28379ab37e18_v2_schema.py index 8fb7011..5014370 100644 --- a/backend/migrations/versions/28379ab37e18_v2_schema.py +++ b/backend/migrations/versions/28379ab37e18_v2_schema.py @@ -1,9 +1,15 @@ """v2 schema Revision ID: 28379ab37e18 -Revises: +Revises: Create Date: 2026-11-15 23:15:51.775907 +Two starting points end at the same schema: +- an empty database: create every table; +- a v1 database: created by v1's `Base.metadata.create_all()`, so it has + tables but no alembic_version. It's upgraded in place and keeps its data + (see _upgrade_v1_schema). Running the create path there fails with + "relation users already exists", which is what broke the first deploy. """ from typing import Sequence, Union @@ -20,6 +26,13 @@ def upgrade() -> None: """Upgrade schema.""" + if sa.inspect(op.get_bind()).has_table("users"): + _upgrade_v1_schema() + else: + _create_v2_schema() + + +def _create_v2_schema() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), @@ -111,6 +124,13 @@ def upgrade() -> None: sa.UniqueConstraint('item_id', 'event_type', name='uq_engagement_item_event') ) op.create_index(op.f('ix_engagement_events_user_id'), 'engagement_events', ['user_id'], unique=False) + _create_recall_tables() + # users <-> recall_cards is circular, so this FK is added once both exist. + op.create_foreign_key('fk_users_pending_recall_card', 'users', 'recall_cards', + ['pending_recall_card_id'], ['id'], ondelete='SET NULL') + + +def _create_recall_tables() -> None: op.create_table('recall_cards', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), @@ -148,10 +168,125 @@ def upgrade() -> None: ) op.create_index(op.f('ix_recall_reviews_card_id'), 'recall_reviews', ['card_id'], unique=False) op.create_index(op.f('ix_recall_reviews_user_id'), 'recall_reviews', ['user_id'], unique=False) + + +# ── v1 -> v2 in place ───────────────────────────────────────────────────────── +# Each step checks what's there first: a v1 database may predate some v1 +# columns too, and a half-applied manual fix shouldn't make this fail. + +WORDS_PER_MINUTE = 238 # app.worker.WORDS_PER_MINUTE at the time of writing + + +def _columns(table: str) -> set[str]: + return {c["name"] for c in sa.inspect(op.get_bind()).get_columns(table)} + + +def _indexes(table: str) -> set[str]: + return {i["name"] for i in sa.inspect(op.get_bind()).get_indexes(table)} + + +def _add_column(table: str, column: sa.Column) -> None: + if column.name not in _columns(table): + op.add_column(table, column) + + +def _set_fk(table: str, column: str, ref_table: str, ondelete: str) -> None: + """v1 foreign keys had no ON DELETE rule; replace them with v2's, using + the name Postgres gives a fresh database's constraint.""" + for fk in sa.inspect(op.get_bind()).get_foreign_keys(table): + if fk["constrained_columns"] == [column]: + op.drop_constraint(fk["name"], table, type_="foreignkey") + op.create_foreign_key(f"{table}_{column}_fkey", table, ref_table, [column], ["id"], ondelete=ondelete) + + +def _create_index(name: str, table: str, columns: list[str], unique: bool = False) -> None: + if name not in _indexes(table): + op.create_index(name, table, columns, unique=unique) + + +def _upgrade_v1_schema() -> None: + from app.url_utils import canonicalize_url + + bind = op.get_bind() + + # users + _add_column("users", sa.Column("interest_profile_embedding", sa.ARRAY(sa.Float()), nullable=True)) + _add_column("users", sa.Column("interest_vector", sa.ARRAY(sa.Float()), nullable=True)) + _add_column("users", sa.Column("recall_enabled", sa.Boolean(), server_default="true", nullable=False)) + _add_column("users", sa.Column("pending_recall_card_id", sa.Integer(), nullable=True)) + + # connection_codes / loopwire_sends + _set_fk("connection_codes", "user_id", "users", "CASCADE") + _add_column("loopwire_sends", sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True)) + _set_fk("loopwire_sends", "user_id", "users", "CASCADE") + _create_index("ix_loopwire_sends_user_id", "loopwire_sends", ["user_id"]) + + # saved_items: new columns + op.alter_column("saved_items", "status", type_=sa.String(length=24), existing_type=sa.String(length=20), + existing_nullable=False) + for column in ( + sa.Column("canonical_url", sa.Text(), nullable=True), # NOT NULL once backfilled below + sa.Column("attempts", sa.Integer(), server_default="0", nullable=False), + sa.Column("processing_started_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("word_count", sa.Integer(), nullable=True), + sa.Column("duration_seconds", sa.Integer(), nullable=True), + sa.Column("summarization_error", sa.Text(), nullable=True), + sa.Column("embedding", sa.ARRAY(sa.Float()), nullable=True), + sa.Column("dispatch_rank", sa.Integer(), nullable=True), + sa.Column("is_exploration", sa.Boolean(), server_default="false", nullable=False), + ): + _add_column("saved_items", column) + + # canonical_url: dedupe key for future saves. Existing duplicates are kept + # (they may have engagement history) but get a suffix so the per-user + # unique constraint holds; only the oldest copy matches new saves. + seen: set[tuple[int, str]] = set() + updates = [] + for item_id, user_id, url in bind.execute(sa.text( + "SELECT id, user_id, url FROM saved_items WHERE canonical_url IS NULL ORDER BY id")): + canonical = canonicalize_url(url) + if (user_id, canonical) in seen: + canonical = f"{canonical}#loopwire-duplicate-{item_id}" + seen.add((user_id, canonical)) + updates.append({"id": item_id, "c": canonical}) + if updates: + bind.execute(sa.text("UPDATE saved_items SET canonical_url = :c WHERE id = :id"), updates) + op.alter_column("saved_items", "canonical_url", existing_type=sa.Text(), nullable=False) + + # v1's read time was an LLM guess from truncated text; v2 computes it from + # the word count. (YouTube needs the video duration, which v1 never stored.) + bind.execute(sa.text( + "UPDATE saved_items SET word_count = array_length(regexp_split_to_array(btrim(clean_text), '\\s+'), 1) " + "WHERE word_count IS NULL AND clean_text IS NOT NULL AND btrim(clean_text) <> ''")) + bind.execute(sa.text( + f"UPDATE saved_items SET estimated_read_time_minutes = GREATEST(1, ROUND(word_count / {WORDS_PER_MINUTE}.0)) " + "WHERE word_count > 0 AND type <> 'youtube'")) + + _set_fk("saved_items", "user_id", "users", "CASCADE") + _set_fk("saved_items", "loopwire_send_id", "loopwire_sends", "SET NULL") + _create_index("ix_saved_items_user_id", "saved_items", ["user_id"]) + _create_index("ix_saved_items_loopwire_send_id", "saved_items", ["loopwire_send_id"]) + _create_index("ix_saved_items_status", "saved_items", ["status"]) + op.create_unique_constraint("uq_saved_items_user_canonical_url", "saved_items", ["user_id", "canonical_url"]) + + # engagement_events. v1 "opened" meant "was sent" (one pixel per item, and + # every dashboard load), and v1 "skipped" was inferred for unopened emails + # too; v2 ranking treats both as noise, so they're removed rather than left + # to skew the interest vector. Clicks are kept, one row per item. + bind.execute(sa.text("DELETE FROM engagement_events WHERE event_type IN ('opened', 'skipped')")) + bind.execute(sa.text( + "DELETE FROM engagement_events a USING engagement_events b " + "WHERE a.item_id = b.item_id AND a.event_type = b.event_type AND a.id > b.id")) + _set_fk("engagement_events", "user_id", "users", "CASCADE") + _set_fk("engagement_events", "item_id", "saved_items", "CASCADE") + _create_index("ix_engagement_events_user_id", "engagement_events", ["user_id"]) + op.create_unique_constraint("uq_engagement_item_event", "engagement_events", ["item_id", "event_type"]) + + # new in v2 + _create_recall_tables() # users <-> recall_cards is circular, so this FK is added once both exist. op.create_foreign_key('fk_users_pending_recall_card', 'users', 'recall_cards', ['pending_recall_card_id'], ['id'], ondelete='SET NULL') - # ### end Alembic commands ### def downgrade() -> None: diff --git a/backend/tests/fixtures/v1_schema.sql b/backend/tests/fixtures/v1_schema.sql new file mode 100644 index 0000000..3a4e353 --- /dev/null +++ b/backend/tests/fixtures/v1_schema.sql @@ -0,0 +1,82 @@ +-- v1 schema: what v1's Base.metadata.create_all() created (backend/app/models.py at +-- commit 402f117, the last release before Alembic). Used by test_migrations.py to +-- prove a pre-migration database upgrades in place. Do not edit. + +CREATE TABLE users ( + id SERIAL NOT NULL, + email VARCHAR(255) NOT NULL, + google_id VARCHAR(255) NOT NULL, + telegram_chat_id BIGINT, + interest_profile_text TEXT, + interest_vector FLOAT[], + created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, + PRIMARY KEY (id), + UNIQUE (telegram_chat_id) +); +CREATE UNIQUE INDEX ix_users_email ON users (email); +CREATE UNIQUE INDEX ix_users_google_id ON users (google_id); + +CREATE TABLE connection_codes ( + id SERIAL NOT NULL, + code VARCHAR(16) NOT NULL, + user_id INTEGER NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, + used_at TIMESTAMP WITH TIME ZONE, + PRIMARY KEY (id), + FOREIGN KEY(user_id) REFERENCES users (id) +); +CREATE UNIQUE INDEX ix_connection_codes_code ON connection_codes (code); + +CREATE TABLE loopwire_sends ( + id SERIAL NOT NULL, + user_id INTEGER NOT NULL, + period VARCHAR(20) NOT NULL, + sent_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, + item_count INTEGER NOT NULL, + email_sent BOOLEAN NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY(user_id) REFERENCES users (id) +); +CREATE INDEX ix_loopwire_sends_user_id ON loopwire_sends (user_id); + +CREATE TABLE saved_items ( + id SERIAL NOT NULL, + user_id INTEGER NOT NULL, + url TEXT NOT NULL, + type VARCHAR(20) NOT NULL, + status VARCHAR(20) NOT NULL, + raw_message_text TEXT, + telegram_user_id BIGINT, + telegram_chat_id BIGINT, + added_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, + title TEXT, + author TEXT, + published_date VARCHAR(50), + clean_text TEXT, + extraction_success BOOLEAN, + extraction_error TEXT, + extracted_at TIMESTAMP WITH TIME ZONE, + summary TEXT, + key_takeaway TEXT, + relevance_note TEXT, + estimated_read_time_minutes INTEGER, + summarized_at TIMESTAMP WITH TIME ZONE, + embedding FLOAT[], + loopwire_send_id INTEGER, + PRIMARY KEY (id), + FOREIGN KEY(user_id) REFERENCES users (id), + FOREIGN KEY(loopwire_send_id) REFERENCES loopwire_sends (id) +); +CREATE INDEX ix_saved_items_user_id ON saved_items (user_id); + +CREATE TABLE engagement_events ( + id SERIAL NOT NULL, + user_id INTEGER NOT NULL, + item_id INTEGER NOT NULL, + event_type VARCHAR(20) NOT NULL, + timestamp TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY(user_id) REFERENCES users (id), + FOREIGN KEY(item_id) REFERENCES saved_items (id) +); +CREATE INDEX ix_engagement_events_user_id ON engagement_events (user_id); diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py new file mode 100644 index 0000000..2f5323d --- /dev/null +++ b/backend/tests/test_migrations.py @@ -0,0 +1,105 @@ +"""Migrations against real databases, both starting points: + +- empty database -> head +- a v1 database (created by v1's create_all, never migrated, with data) -> head + +The second is what production looked like on the first Alembic deploy, which +failed with `relation "users" already exists`. Each case gets its own +throwaway database next to the test database. +""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest +from sqlalchemy import create_engine, text +from sqlalchemy.engine import make_url + +BACKEND = Path(__file__).resolve().parent.parent +V1_SCHEMA = Path(__file__).resolve().parent / "fixtures" / "v1_schema.sql" +TEST_URL = make_url(os.environ["DATABASE_URL"]) + + +@pytest.fixture +def scratch_db(request): + name = f"loopwire_mig_{request.node.name.removeprefix('test_')}"[:60] + admin = create_engine(TEST_URL.set(database="postgres"), isolation_level="AUTOCOMMIT") + with admin.connect() as c: + c.execute(text(f'DROP DATABASE IF EXISTS "{name}"')) + c.execute(text(f'CREATE DATABASE "{name}"')) + url = TEST_URL.set(database=name) + engine = create_engine(url) + yield url, engine + engine.dispose() + with admin.connect() as c: + c.execute(text(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')) + admin.dispose() + + +def alembic(url, *args: str) -> subprocess.CompletedProcess: + env = {**os.environ, "DATABASE_URL": url.render_as_string(hide_password=False)} + return subprocess.run([sys.executable, "-m", "alembic", *args], cwd=BACKEND, env=env, capture_output=True, text=True) + + +def assert_at_head_without_drift(url): + upgrade = alembic(url, "upgrade", "head") + assert upgrade.returncode == 0, upgrade.stderr + check = alembic(url, "check") + assert check.returncode == 0, check.stdout + check.stderr + + +def test_empty_database(scratch_db): + url, _ = scratch_db + assert_at_head_without_drift(url) + + +def test_v1_database_upgrades_in_place(scratch_db): + url, engine = scratch_db + long_text = " ".join(["word"] * 2380) + with engine.begin() as c: + c.exec_driver_sql(V1_SCHEMA.read_text()) + c.execute(text("INSERT INTO users (id, email, google_id, telegram_chat_id) VALUES " + "(1, 'a@example.com', 'g1', 111), (2, 'b@example.com', 'g2', NULL)")) + c.execute(text("INSERT INTO loopwire_sends (id, user_id, period, item_count, email_sent) " + "VALUES (1, 1, 'daily', 3, true)")) + c.execute(text( + "INSERT INTO saved_items (id, user_id, url, type, status, clean_text, estimated_read_time_minutes, " + "loopwire_send_id) VALUES " + "(1, 1, 'https://example.com/post?utm_source=x', 'article', 'summarized', :t, 15, 1), " + "(2, 1, 'https://example.com/post', 'article', 'summarized', 'short text', 3, 1), " + "(3, 1, 'https://www.youtube.com/watch?v=abc', 'youtube', 'summarized', 'a transcript', 12, 1), " + "(4, 2, 'https://example.com/post', 'article', 'pending', NULL, NULL, NULL)"), {"t": long_text}) + c.execute(text("INSERT INTO engagement_events (user_id, item_id, event_type) VALUES " + "(1, 1, 'opened'), (1, 1, 'opened'), (1, 1, 'clicked_source'), (1, 1, 'clicked_source'), " + "(1, 2, 'opened'), (1, 2, 'skipped')")) + + assert_at_head_without_drift(url) + + with engine.connect() as c: + items = {r.id: r for r in c.execute(text( + "SELECT id, canonical_url, word_count, estimated_read_time_minutes FROM saved_items"))} + events = c.execute(text("SELECT item_id, event_type FROM engagement_events")).all() + users = c.execute(text("SELECT count(*) FROM users WHERE recall_enabled")).scalar() + + # every row survives; the later duplicate is kept but can't collide with the original + assert len(items) == 4 and users == 2 + assert items[1].canonical_url == "https://example.com/post" + assert items[2].canonical_url == "https://example.com/post#loopwire-duplicate-2" + assert items[4].canonical_url == "https://example.com/post" # another user's copy is untouched + # read time recomputed from the real word count; YouTube keeps v1's value (no duration stored) + assert (items[1].word_count, items[1].estimated_read_time_minutes) == (2380, 10) + assert items[3].estimated_read_time_minutes == 12 + # v1 "opened"/"skipped" are noise under v2 semantics; clicks are kept once + assert events == [(1, "clicked_source")] + + +def test_v2_database_is_left_alone(scratch_db): + url, engine = scratch_db + assert_at_head_without_drift(url) + with engine.begin() as c: + c.execute(text("INSERT INTO users (email, google_id) VALUES ('a@example.com', 'g1')")) + assert_at_head_without_drift(url) # re-running on deploy is a no-op + with engine.connect() as c: + assert c.execute(text("SELECT count(*) FROM users")).scalar() == 1 diff --git a/backend/tests/test_personalization_and_dispatch.py b/backend/tests/test_personalization_and_dispatch.py index 8b109a6..c7036ea 100644 --- a/backend/tests/test_personalization_and_dispatch.py +++ b/backend/tests/test_personalization_and_dispatch.py @@ -180,6 +180,22 @@ def test_exploration_pick_gets_honest_note(db, make_user, make_item): assert pick.item_id == explorer.id and pick.relevance_note == EXPLORATION_NOTE +def test_profile_embedding_failure_does_not_block_the_dispatch(db, make_user, make_item, monkeypatch): + """Users migrated from v1 have profile text but no profile embedding, so + their first v2 dispatch computes it. If that call fails, the dispatch still + goes out (ranked without the profile) and the embedding is retried later.""" + def boom(text): + raise RuntimeError("quota exceeded") + + monkeypatch.setattr("app.personalization.compute_embedding", boom) + user = make_user(profile="LLM engineering") + make_item(user) + bundle = build_loopwire_send(db, user.id) + assert bundle is not None and len(bundle.items) == 1 + assert bundle.ctx.profile_vector is None + assert db.get(models.User, user.id).interest_profile_embedding is None + + def test_daily_cap_uses_local_day(db, make_user, monkeypatch): user = make_user() # 23:00 IST yesterday == 17:30 UTC yesterday: different local day