Files
FabledCurator/backend/app/services/artist_service.py
T
bvandeusen 2f66de2928
CI / lint (push) Failing after 3s
CI / backend-lint-and-test (push) Successful in 11s
CI / frontend-build (push) Successful in 17s
CI / intimp (push) Failing after 2m15s
CI / intapi (push) Failing after 2m18s
CI / intcore (push) Failing after 2m17s
feat(model): nullable Post.source_id + denormalized Post.artist_id; retire sidecar synthetics
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.
2026-06-01 14:17:52 -04:00

255 lines
8.7 KiB
Python

"""Artist overview + paged images.
Images are linked to an artist through the provenance chain
Source(artist_id) -> ImageProvenance(source_id) -> ImageRecord. DISTINCT
guards against an image having several provenance rows for one artist.
Dates come from Post.post_date via ImageProvenance.post_id.
"""
from dataclasses import dataclass
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from ..models import (
Artist,
ImageProvenance,
ImageRecord,
Post,
Source,
Tag,
)
from ..models.tag import image_tag
from ..utils.slug import slugify
from .gallery_service import decode_cursor, encode_cursor, thumbnail_url
@dataclass(frozen=True)
class ArtistImagesPage:
images: list[dict]
next_cursor: str | None
class ArtistService:
def __init__(self, session: AsyncSession):
self.session = session
async def _artist_by_slug(self, slug: str) -> Artist | None:
return (
await self.session.execute(
select(Artist).where(Artist.slug == slug)
)
).scalar_one_or_none()
async def overview(self, slug: str) -> dict | None:
artist = await self._artist_by_slug(slug)
if artist is None:
return None
aid = artist.id
img_join = (
select(ImageRecord.id).where(ImageRecord.artist_id == aid)
)
image_count = (
await self.session.execute(
select(func.count(ImageRecord.id))
.where(ImageRecord.artist_id == aid)
)
).scalar_one()
# Posts under this artist that have at least one image attached.
# Use Post.artist_id (alembic 0030) for the artist filter; keep
# the ImageProvenance JOIN so date bounds reflect only image-
# bearing posts (matches the original semantic). NULL-source
# posts now surface too.
date_row = (
await self.session.execute(
select(func.min(Post.post_date), func.max(Post.post_date))
.select_from(Post)
.join(ImageProvenance, ImageProvenance.post_id == Post.id)
.where(Post.artist_id == aid)
)
).first()
dmin, dmax = date_row if date_row else (None, None)
cooccurring = (
await self.session.execute(
select(
Tag.id, Tag.name, Tag.kind,
func.count(image_tag.c.image_record_id).label("cnt"),
)
.select_from(Tag)
.join(image_tag, image_tag.c.tag_id == Tag.id)
.where(image_tag.c.image_record_id.in_(img_join))
.group_by(Tag.id, Tag.name, Tag.kind)
.order_by(func.count(image_tag.c.image_record_id).desc())
.limit(20)
)
).all()
sources = (
await self.session.execute(
select(
Source.id, Source.platform, Source.url,
func.count(func.distinct(ImageProvenance.image_record_id)).label("cnt"),
)
.select_from(Source)
.outerjoin(ImageProvenance, ImageProvenance.source_id == Source.id)
.where(Source.artist_id == aid)
.group_by(Source.id, Source.platform, Source.url)
.order_by(Source.id)
)
).all()
# Same Post.artist_id direct filter — counts NULL-source posts too.
month = func.date_trunc("month", Post.post_date).label("m")
activity = (
await self.session.execute(
select(month, func.count(func.distinct(ImageProvenance.image_record_id)))
.select_from(Post)
.join(ImageProvenance, ImageProvenance.post_id == Post.id)
.where(and_(Post.artist_id == aid, Post.post_date.isnot(None)))
.group_by(month)
.order_by(month)
)
).all()
post_count = (
await self.session.execute(
select(func.count(func.distinct(Post.id)))
.where(Post.artist_id == aid)
)
).scalar_one()
return {
"id": artist.id,
"name": artist.name,
"slug": artist.slug,
"is_subscription": bool(artist.is_subscription),
"image_count": int(image_count),
"post_count": int(post_count),
"date_range": {
"min": dmin.isoformat() if dmin else None,
"max": dmax.isoformat() if dmax else None,
},
"cooccurring_tags": [
{
"id": tid,
"name": name,
"kind": kind.value if hasattr(kind, "value") else kind,
"count": int(cnt),
}
for tid, name, kind, cnt in cooccurring
],
"sources": [
{
"id": sid,
"platform": platform,
"url": url,
"image_count": int(cnt),
}
for sid, platform, url, cnt in sources
],
"activity": [
{"month": m.isoformat(), "count": int(cnt)}
for m, cnt in activity
],
}
async def images(
self, slug: str, cursor: str | None, limit: int = 60
) -> ArtistImagesPage | None:
if limit < 1 or limit > 200:
raise ValueError("limit must be between 1 and 200")
artist = await self._artist_by_slug(slug)
if artist is None:
return None
# Dedupe via IN-subquery rather than JOIN + DISTINCT: an image can
# have several provenance rows for one artist, and SELECT DISTINCT
# over ImageRecord fails in Postgres because its json columns have
# no equality operator.
stmt = select(ImageRecord).where(
ImageRecord.artist_id == artist.id
)
if cursor:
cur_ts, cur_id = decode_cursor(cursor)
stmt = stmt.where(
or_(
ImageRecord.created_at < cur_ts,
and_(ImageRecord.created_at == cur_ts, ImageRecord.id < cur_id),
)
)
stmt = stmt.order_by(
ImageRecord.created_at.desc(), ImageRecord.id.desc()
).limit(limit + 1)
rows = (await self.session.execute(stmt)).scalars().all()
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = encode_cursor(last.created_at, last.id)
rows = rows[:limit]
return ArtistImagesPage(
images=[
{
"id": r.id,
"sha256": r.sha256,
"mime": r.mime,
"width": r.width,
"height": r.height,
"thumbnail_url": thumbnail_url(r.thumbnail_path, r.sha256, r.mime),
}
for r in rows
],
next_cursor=next_cursor,
)
async def find_or_create(self, name: str) -> tuple[Artist, bool]:
"""Return (artist, created). Slug-keyed; idempotent under races."""
cleaned = (name or "").strip()
if not cleaned:
raise ValueError("artist name must not be empty")
slug = slugify(cleaned)
existing = (await self.session.execute(
select(Artist).where(Artist.slug == slug)
)).scalar_one_or_none()
if existing is not None:
return existing, False
artist = Artist(name=cleaned, slug=slug)
self.session.add(artist)
try:
await self.session.flush()
except IntegrityError:
await self.session.rollback()
existing = (await self.session.execute(
select(Artist).where(Artist.slug == slug)
)).scalar_one()
return existing, False
await self.session.commit()
return artist, True
async def autocomplete(self, prefix: str, limit: int = 20) -> list[Artist]:
cleaned = (prefix or "").strip()
if not cleaned:
return []
like = f"%{cleaned.lower()}%"
prefix_like = f"{cleaned.lower()}%"
# Rank: exact (0) < prefix (1) < substring (2).
rank = case(
(func.lower(Artist.name) == cleaned.lower(), 0),
(func.lower(Artist.name).like(prefix_like), 1),
else_=2,
).label("rank")
rows = (await self.session.execute(
select(Artist, rank)
.where(func.lower(Artist.name).like(like))
.order_by(rank, Artist.name.asc())
.limit(limit)
)).all()
return [a for a, _ in rows]