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.
124 lines
4.1 KiB
Python
124 lines
4.1 KiB
Python
"""Read-only provenance queries.
|
|
|
|
Provenance is its own system, intentionally separate from the tag/ML
|
|
system (see project_provenance_separation). This service joins
|
|
ImageProvenance -> Post/Source/Artist and returns plain dicts. It never
|
|
mutates and never imports tag/ML modules.
|
|
"""
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from ..models import (
|
|
Artist,
|
|
ImageProvenance,
|
|
ImageRecord,
|
|
Post,
|
|
PostAttachment,
|
|
Source,
|
|
)
|
|
from ..utils.html_sanitize import sanitize_post_html
|
|
|
|
|
|
def _post_dict(p: Post) -> dict:
|
|
return {
|
|
"id": p.id,
|
|
"external_post_id": p.external_post_id,
|
|
"url": p.post_url,
|
|
"title": p.post_title,
|
|
"date": p.post_date.isoformat() if p.post_date else None,
|
|
"description_html": sanitize_post_html(p.description),
|
|
"attachment_count": p.attachment_count,
|
|
}
|
|
|
|
|
|
def _source_dict(s: Source) -> dict:
|
|
return {"id": s.id, "platform": s.platform, "url": s.url}
|
|
|
|
|
|
def _artist_dict(a: Artist) -> dict:
|
|
return {"id": a.id, "name": a.name, "slug": a.slug}
|
|
|
|
|
|
def _attachment_dict(a: PostAttachment) -> dict:
|
|
return {
|
|
"id": a.id,
|
|
"original_filename": a.original_filename,
|
|
"size_bytes": a.size_bytes,
|
|
"ext": a.ext,
|
|
"download_url": f"/api/attachments/{a.id}/download",
|
|
}
|
|
|
|
|
|
class ProvenanceService:
|
|
def __init__(self, session: AsyncSession):
|
|
self.session = session
|
|
|
|
async def _attachments_for_posts(self, post_ids: list[int]) -> list[dict]:
|
|
if not post_ids:
|
|
return []
|
|
rows = (
|
|
await self.session.execute(
|
|
select(PostAttachment)
|
|
.where(PostAttachment.post_id.in_(post_ids))
|
|
.order_by(PostAttachment.id.asc())
|
|
)
|
|
).scalars().all()
|
|
return [_attachment_dict(a) for a in rows]
|
|
|
|
async def for_image(self, image_id: int) -> dict | None:
|
|
rec = await self.session.get(ImageRecord, image_id)
|
|
if rec is None:
|
|
return None
|
|
# Artist via Post.artist_id (alembic 0030); Source via LEFT JOIN
|
|
# since both Post.source_id and ImageProvenance.source_id can be
|
|
# NULL for filesystem-imported content. Frontend renders source=
|
|
# null as "filesystem import."
|
|
stmt = (
|
|
select(ImageProvenance, Post, Source, Artist)
|
|
.join(Post, Post.id == ImageProvenance.post_id)
|
|
.join(Artist, Artist.id == Post.artist_id)
|
|
.outerjoin(Source, Source.id == ImageProvenance.source_id)
|
|
.where(ImageProvenance.image_record_id == image_id)
|
|
.order_by(ImageProvenance.captured_at.asc(),
|
|
ImageProvenance.id.asc())
|
|
)
|
|
rows = (await self.session.execute(stmt)).all()
|
|
post_ids = [ip.post_id for ip, _p, _s, _a in rows]
|
|
attachments = await self._attachments_for_posts(post_ids)
|
|
return {
|
|
"image_id": image_id,
|
|
"provenance": [
|
|
{
|
|
"provenance_id": ip.id,
|
|
"captured_at": ip.captured_at.isoformat()
|
|
if ip.captured_at else None,
|
|
"post": _post_dict(post),
|
|
"source": _source_dict(src) if src is not None else None,
|
|
"artist": _artist_dict(art),
|
|
}
|
|
for ip, post, src, art in rows
|
|
],
|
|
"attachments": attachments,
|
|
}
|
|
|
|
async def for_post(self, post_id: int) -> dict | None:
|
|
# Same LEFT JOIN to Source — get_post must succeed for a
|
|
# NULL-source post.
|
|
stmt = (
|
|
select(Post, Source, Artist)
|
|
.join(Artist, Artist.id == Post.artist_id)
|
|
.outerjoin(Source, Source.id == Post.source_id)
|
|
.where(Post.id == post_id)
|
|
)
|
|
row = (await self.session.execute(stmt)).first()
|
|
if row is None:
|
|
return None
|
|
post, src, art = row
|
|
return {
|
|
"post": _post_dict(post),
|
|
"source": _source_dict(src) if src is not None else None,
|
|
"artist": _artist_dict(art),
|
|
"attachments": await self._attachments_for_posts([post.id]),
|
|
}
|