2f66de2928
Operator-asked 2026-06-01 after the Dymkens orphan investigation (Scribe plan #540). The pre-2030 sidecar-synthetic Source pattern (`sidecar:<platform>:<slug>` enabled=false rows) existed solely to satisfy `Post.source_id NOT NULL`, and leaked into the Subscriptions UI as phantom subscriptions. Now the data model says what's true: filesystem-imported content with no live subscription has NULL source_id, full stop. ## Schema (alembic 0030) - `post.artist_id` — NEW NOT NULL FK to artist (CASCADE). Backfilled from source.artist_id in the migration. Indexed for the artist-filter queries. - `post.source_id` — NOT NULL → nullable; FK ondelete CASCADE → SET NULL. Deleting a Source detaches its Posts instead of destroying archived content (subscription ends, archive stays). - `image_provenance.source_id` — same nullable + SET NULL. - Partial unique index `uq_post_artist_external_id_null_source` on (artist_id, external_post_id) WHERE source_id IS NULL — guards filesystem-import dedup since the existing source-bound unique ignores NULLs (Postgres treats NULL != NULL). - Sidecar synthetic Sources deleted: NULL out FKs in post, image_provenance first, then DELETE FROM source WHERE url LIKE 'sidecar:%'. The Dymkens cleanup. ## Model + service changes - `Post.source_id` → `Mapped[int | None]`; new `Post.artist_id` denormalized. - `ImageProvenance.source_id` → `Mapped[int | None]`. - Importer: `_source_for_sidecar` (synthetic-creating) → `_lookup_source_for_sidecar` (returns None when no subscription). `_find_or_create_post` takes required `artist_id`; matches on (source_id, external_post_id) for source-bound posts or (artist_id, external_post_id) for NULL-source posts. - Service queries switched off the Source detour to use Post.artist_id directly: post_feed_service.scroll/around/get_post (LEFT JOIN to Source so NULL-source posts surface); artist_service date_row/ activity/post_count; provenance_service.for_image/for_post (LEFT JOIN); gallery_service._provenance_exists_where_artist via Post.artist_id instead of ImageProvenance.source_id → Source. - `_to_dict` and provenance dict-builders emit `"source": null` for NULL-source rows. ## Frontend - `ProvenancePanel.vue` + `PostCard.vue`: render `e.source?.platform ?? 'filesystem import'` so NULL-source posts get a clear "filesystem import" affordance instead of a NaN crash. ## Tests - `test_importer_upsert_helpers`: removed the four synthetic-anchor tests; added `_find_or_create_post_idempotent_with_null_source` (dedup via the partial unique index) and `_lookup_source_for_sidecar_returns_*` (existing-subscription + none cases). The existing `_find_or_create_post_idempotent` now also passes `artist_id` and asserts it. - 8 other test files updated: every direct `Post(...)` construction gains `artist_id=<artist>.id`. The `_seed_post` helper in `test_post_feed_service` looks up artist_id from the source row so callsites stay one-arg. ## Verification on deploy After alembic 0030 runs: - `SELECT COUNT(*) FROM source WHERE url LIKE 'sidecar:%'` → 0. - `SELECT COUNT(*) FROM post WHERE source_id IS NULL` → count of filesystem-imported posts (Dymkens + any other historical). - Every `post.artist_id` non-null; consistent with source.artist_id for source-bound rows. - Subscriptions tab: no Dymkens phantom row. - Artist detail → Posts/Gallery: Dymkens's content still reachable via Post.artist_id. - Provenance panel renders "filesystem import" chip for NULL-source posts; PostCard same. ## Out of scope - UI to manage/delete orphan NULL-source Posts. Data model is right; UI follows if operator wants it.
341 lines
11 KiB
Python
341 lines
11 KiB
Python
"""FC-3e: PostFeedService unit tests.
|
|
|
|
Covers cursor encode/decode, ordering (coalesce(post_date,
|
|
downloaded_at) DESC, id DESC), artist/platform filters, pagination
|
|
boundary, and the thumbnails/attachments composition.
|
|
"""
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import pytest
|
|
from sqlalchemy import select
|
|
|
|
from backend.app.models import (
|
|
Artist,
|
|
ImageRecord,
|
|
Post,
|
|
PostAttachment,
|
|
Source,
|
|
)
|
|
from backend.app.services.post_feed_service import (
|
|
PostFeedService,
|
|
decode_cursor,
|
|
encode_cursor,
|
|
)
|
|
|
|
pytestmark = pytest.mark.integration
|
|
|
|
|
|
# --- Cursor round-trip ----------------------------------------------------
|
|
|
|
|
|
def test_cursor_round_trip():
|
|
ts = datetime(2026, 5, 21, 12, 34, 56, tzinfo=UTC)
|
|
c = encode_cursor(ts, 42)
|
|
assert decode_cursor(c) == (ts, 42)
|
|
|
|
|
|
def test_decode_cursor_rejects_garbage():
|
|
with pytest.raises(ValueError):
|
|
decode_cursor("not-base64!!!")
|
|
|
|
|
|
# --- Fixture builders -----------------------------------------------------
|
|
|
|
|
|
async def _seed_artist(db, name: str):
|
|
a = Artist(name=name, slug=name.lower().replace(" ", "-"))
|
|
db.add(a)
|
|
await db.flush()
|
|
return a
|
|
|
|
|
|
async def _seed_source(db, artist_id: int, platform: str, url: str):
|
|
s = Source(artist_id=artist_id, platform=platform, url=url, enabled=True)
|
|
db.add(s)
|
|
await db.flush()
|
|
return s
|
|
|
|
|
|
async def _seed_post(
|
|
db, source_id: int, *, external_id: str,
|
|
post_date=None, downloaded_at=None, title=None, description=None,
|
|
):
|
|
# Post.artist_id is NOT NULL since alembic 0030; look it up from
|
|
# the source so callsites don't have to thread the artist through.
|
|
artist_id = (await db.execute(
|
|
select(Source.artist_id).where(Source.id == source_id)
|
|
)).scalar_one()
|
|
p = Post(
|
|
source_id=source_id, artist_id=artist_id, external_post_id=external_id,
|
|
post_title=title, post_date=post_date,
|
|
description=description,
|
|
)
|
|
if downloaded_at is not None:
|
|
p.downloaded_at = downloaded_at
|
|
db.add(p)
|
|
await db.flush()
|
|
return p
|
|
|
|
|
|
# --- scroll() ordering and pagination ------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_orders_by_coalesce_post_date_then_downloaded_at(db):
|
|
artist = await _seed_artist(db, "alice-order")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-order")
|
|
|
|
now = datetime.now(UTC)
|
|
# post A: post_date older than its downloaded_at; sort key = post_date
|
|
a = await _seed_post(
|
|
db, src.id, external_id="A",
|
|
post_date=now - timedelta(days=10),
|
|
downloaded_at=now,
|
|
)
|
|
# post B: post_date NULL → sort key = downloaded_at
|
|
b = await _seed_post(
|
|
db, src.id, external_id="B",
|
|
post_date=None,
|
|
downloaded_at=now - timedelta(days=5),
|
|
)
|
|
# post C: post_date newest of all
|
|
c = await _seed_post(
|
|
db, src.id, external_id="C",
|
|
post_date=now - timedelta(days=1),
|
|
downloaded_at=now - timedelta(days=20),
|
|
)
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(cursor=None, limit=10)
|
|
ids = [item["id"] for item in page["items"]]
|
|
# Expected order by coalesce(post_date, downloaded_at) DESC:
|
|
# C (1 day ago) > B (5 days ago via downloaded_at) > A (10 days ago)
|
|
assert ids == [c.id, b.id, a.id]
|
|
assert page["next_cursor"] is None # 3 items, limit 10, no more
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_pagination_across_two_pages(db):
|
|
artist = await _seed_artist(db, "alice-page")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-page")
|
|
|
|
now = datetime.now(UTC)
|
|
posts = []
|
|
for i in range(5):
|
|
p = await _seed_post(
|
|
db, src.id, external_id=f"P{i}",
|
|
post_date=now - timedelta(days=i),
|
|
)
|
|
posts.append(p)
|
|
await db.commit()
|
|
|
|
page1 = await PostFeedService(db).scroll(cursor=None, limit=2)
|
|
assert len(page1["items"]) == 2
|
|
assert page1["next_cursor"] is not None
|
|
assert [it["id"] for it in page1["items"]] == [posts[0].id, posts[1].id]
|
|
|
|
page2 = await PostFeedService(db).scroll(cursor=page1["next_cursor"], limit=2)
|
|
assert [it["id"] for it in page2["items"]] == [posts[2].id, posts[3].id]
|
|
assert page2["next_cursor"] is not None
|
|
|
|
page3 = await PostFeedService(db).scroll(cursor=page2["next_cursor"], limit=2)
|
|
assert [it["id"] for it in page3["items"]] == [posts[4].id]
|
|
assert page3["next_cursor"] is None
|
|
|
|
|
|
# --- Filters --------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_filters_by_artist(db):
|
|
alice = await _seed_artist(db, "alice-filter")
|
|
bob = await _seed_artist(db, "bob-filter")
|
|
src_a = await _seed_source(db, alice.id, "patreon", "https://p/alice-f")
|
|
src_b = await _seed_source(db, bob.id, "patreon", "https://p/bob-f")
|
|
now = datetime.now(UTC)
|
|
pa = await _seed_post(db, src_a.id, external_id="PA", post_date=now)
|
|
await _seed_post(db, src_b.id, external_id="PB", post_date=now)
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(
|
|
cursor=None, limit=10, artist_id=alice.id,
|
|
)
|
|
assert [it["id"] for it in page["items"]] == [pa.id]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_filters_by_platform(db):
|
|
artist = await _seed_artist(db, "alice-platf")
|
|
src_p = await _seed_source(db, artist.id, "patreon", "https://p/alice-pp")
|
|
src_d = await _seed_source(db, artist.id, "deviantart", "https://d/alice-dd")
|
|
now = datetime.now(UTC)
|
|
pp = await _seed_post(db, src_p.id, external_id="PP", post_date=now)
|
|
await _seed_post(db, src_d.id, external_id="PD", post_date=now)
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(
|
|
cursor=None, limit=10, platform="patreon",
|
|
)
|
|
assert [it["id"] for it in page["items"]] == [pp.id]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_combined_artist_and_platform(db):
|
|
alice = await _seed_artist(db, "alice-combo")
|
|
bob = await _seed_artist(db, "bob-combo")
|
|
src_alice_patreon = await _seed_source(db, alice.id, "patreon", "https://p/alice-c")
|
|
src_alice_da = await _seed_source(db, alice.id, "deviantart", "https://d/alice-c")
|
|
src_bob_patreon = await _seed_source(db, bob.id, "patreon", "https://p/bob-c")
|
|
now = datetime.now(UTC)
|
|
target = await _seed_post(
|
|
db, src_alice_patreon.id, external_id="TARGET", post_date=now,
|
|
)
|
|
# Distractors — wrong platform for alice, wrong artist for patreon.
|
|
await _seed_post(db, src_alice_da.id, external_id="DA", post_date=now)
|
|
await _seed_post(db, src_bob_patreon.id, external_id="BP", post_date=now)
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(
|
|
cursor=None, limit=10, artist_id=alice.id, platform="patreon",
|
|
)
|
|
assert [it["id"] for it in page["items"]] == [target.id]
|
|
|
|
|
|
# --- Dict shape and content ----------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_item_shape_minimal(db):
|
|
artist = await _seed_artist(db, "alice-shape")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-sh")
|
|
now = datetime.now(UTC)
|
|
await _seed_post(
|
|
db, src.id, external_id="SHAPE", post_date=now,
|
|
title="Hello", description="<p>world</p>",
|
|
)
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(cursor=None, limit=10)
|
|
item = page["items"][0]
|
|
assert set(item.keys()) >= {
|
|
"id", "external_post_id", "post_url", "post_title",
|
|
"post_date", "downloaded_at",
|
|
"description_plain", "description_truncated",
|
|
"artist", "source",
|
|
"thumbnails", "thumbnails_more", "attachments",
|
|
}
|
|
assert item["post_title"] == "Hello"
|
|
assert item["description_plain"] == "world"
|
|
assert item["description_truncated"] is False
|
|
assert item["artist"]["slug"] == "alice-shape"
|
|
assert item["source"]["platform"] == "patreon"
|
|
# List response NEVER carries the full description.
|
|
assert "description_full" not in item
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_description_truncates_long_text(db):
|
|
artist = await _seed_artist(db, "alice-long")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-lo")
|
|
long_text = "word " * 200 # ~1000 chars
|
|
await _seed_post(
|
|
db, src.id, external_id="LONG",
|
|
post_date=datetime.now(UTC),
|
|
description=long_text,
|
|
)
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(cursor=None, limit=10)
|
|
item = page["items"][0]
|
|
assert item["description_truncated"] is True
|
|
assert len(item["description_plain"]) <= 281 # 280 + ellipsis char
|
|
|
|
|
|
# --- Thumbnails composition (primary_post_id linkage) --------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_thumbnails_show_first_six_with_overflow_count(db):
|
|
artist = await _seed_artist(db, "alice-thumbs")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-th")
|
|
post = await _seed_post(
|
|
db, src.id, external_id="THUMB",
|
|
post_date=datetime.now(UTC),
|
|
)
|
|
# Seed 8 ImageRecords linked to this post (unique sha + path each).
|
|
for i in range(8):
|
|
db.add(ImageRecord(
|
|
path=f"/images/thumb-{post.id}-{i}.jpg",
|
|
sha256=f"{post.id:02d}" + f"{i:062d}",
|
|
size_bytes=10, mime="image/jpeg", width=10, height=10,
|
|
origin="downloaded", primary_post_id=post.id,
|
|
artist_id=artist.id,
|
|
))
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(cursor=None, limit=10)
|
|
item = page["items"][0]
|
|
assert len(item["thumbnails"]) == 6
|
|
assert item["thumbnails_more"] == 2
|
|
for t in item["thumbnails"]:
|
|
assert "image_id" in t
|
|
assert t["thumbnail_url"].startswith("/images/thumbs/")
|
|
assert t["mime"] == "image/jpeg"
|
|
|
|
|
|
# --- Attachments composition ---------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_scroll_attachments_returns_non_media_files(db):
|
|
artist = await _seed_artist(db, "alice-att")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-at")
|
|
post = await _seed_post(
|
|
db, src.id, external_id="ATT", post_date=datetime.now(UTC),
|
|
)
|
|
db.add(PostAttachment(
|
|
post_id=post.id, artist_id=artist.id,
|
|
sha256="a" * 64, path="/images/att/x.pdf",
|
|
original_filename="notes.pdf", ext="pdf",
|
|
mime="application/pdf", size_bytes=12345,
|
|
))
|
|
await db.commit()
|
|
|
|
page = await PostFeedService(db).scroll(cursor=None, limit=10)
|
|
item = page["items"][0]
|
|
assert len(item["attachments"]) == 1
|
|
att = item["attachments"][0]
|
|
assert att["original_filename"] == "notes.pdf"
|
|
assert att["ext"] == "pdf"
|
|
assert att["mime"] == "application/pdf"
|
|
assert att["size_bytes"] == 12345
|
|
assert att["download_url"] == f"/api/attachments/{att['id']}/download"
|
|
|
|
|
|
# --- get_post() detail ---------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_post_returns_full_description(db):
|
|
artist = await _seed_artist(db, "alice-detail")
|
|
src = await _seed_source(db, artist.id, "patreon", "https://p/alice-de")
|
|
long_text = "word " * 200
|
|
p = await _seed_post(
|
|
db, src.id, external_id="DETAIL",
|
|
post_date=datetime.now(UTC),
|
|
description=long_text,
|
|
)
|
|
await db.commit()
|
|
|
|
item = await PostFeedService(db).get_post(p.id)
|
|
assert item is not None
|
|
assert "description_full" in item
|
|
# Full text is HTML-stripped but NOT truncated.
|
|
assert len(item["description_full"]) > 280
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_post_unknown_returns_none(db):
|
|
item = await PostFeedService(db).get_post(99999)
|
|
assert item is None
|