Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 10 additions & 1 deletion backend/app/personalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"""

import datetime as dt
import logging
from dataclasses import dataclass

import numpy as np
Expand All @@ -39,6 +40,8 @@
User,
)

logger = logging.getLogger("loopwire.personalization")

SIGNAL_WEIGHTS = {
EVENT_FEEDBACK_UP: 2.0,
EVENT_CLICKED_SOURCE: 1.0,
Expand Down Expand Up @@ -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


Expand Down
139 changes: 137 additions & 2 deletions backend/migrations/versions/28379ab37e18_v2_schema.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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),
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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:
Expand Down
82 changes: 82 additions & 0 deletions backend/tests/fixtures/v1_schema.sql
Original file line number Diff line number Diff line change
@@ -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);
Loading
Loading