Files
FabledCurator/tests/test_provenance_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

181 lines
6.2 KiB
Python

from datetime import UTC, datetime
import pytest
from backend.app.models import (
Artist,
ImageProvenance,
ImageRecord,
Post,
PostAttachment,
Source,
)
from backend.app.services.provenance_service import ProvenanceService
pytestmark = pytest.mark.integration
async def _seed_image(db, sha="a" + "0" * 63) -> ImageRecord:
rec = ImageRecord(
path=f"/images/test/{sha}.jpg",
sha256=sha,
size_bytes=1, mime="image/jpeg", width=1, height=1,
origin="imported_filesystem", integrity_status="unknown",
)
db.add(rec)
await db.flush()
return rec
async def _seed_post(db, *, artist_name, slug, platform, ext_id,
title=None, desc=None, count=None) -> tuple:
artist = Artist(name=artist_name, slug=slug)
db.add(artist)
await db.flush()
source = Source(artist_id=artist.id, platform=platform,
url=f"https://{platform}.test/{slug}")
db.add(source)
await db.flush()
post = Post(
source_id=source.id, artist_id=artist.id, external_post_id=ext_id,
post_url=f"https://{platform}.test/p/{ext_id}",
post_title=title, post_date=datetime(2023, 8, 1, tzinfo=UTC),
description=desc, attachment_count=count,
)
db.add(post)
await db.flush()
return artist, source, post
@pytest.mark.asyncio
async def test_for_image_missing_returns_none(db):
svc = ProvenanceService(db)
assert await svc.for_image(999999) is None
@pytest.mark.asyncio
async def test_for_image_no_provenance_returns_empty_list(db):
rec = await _seed_image(db)
svc = ProvenanceService(db)
payload = await svc.for_image(rec.id)
assert payload == {
"image_id": rec.id, "provenance": [], "attachments": []
}
@pytest.mark.asyncio
async def test_for_image_single_provenance_full_shape(db):
rec = await _seed_image(db)
artist, source, post = await _seed_post(
db, artist_name="Alice", slug="alice", platform="patreon",
ext_id="555", title="Set 1", desc="<p>hi</p><script>x</script>",
count=2,
)
db.add(ImageProvenance(image_record_id=rec.id, post_id=post.id,
source_id=source.id))
await db.flush()
svc = ProvenanceService(db)
payload = await svc.for_image(rec.id)
assert payload["image_id"] == rec.id
assert len(payload["provenance"]) == 1
e = payload["provenance"][0]
assert e["post"]["id"] == post.id
assert e["post"]["external_post_id"] == "555"
assert e["post"]["title"] == "Set 1"
assert e["post"]["attachment_count"] == 2
assert e["post"]["description_html"] == "<p>hi</p>" # script removed
assert e["post"]["url"] == "https://patreon.test/p/555"
assert e["post"]["date"].startswith("2023-08-01")
assert e["source"] == {"id": source.id, "platform": "patreon",
"url": source.url}
assert e["artist"] == {"id": artist.id, "name": "Alice",
"slug": "alice"}
assert e["provenance_id"] is not None
assert e["captured_at"] is not None
@pytest.mark.asyncio
async def test_for_image_multiple_provenance_peer_ordering(db):
rec = await _seed_image(db)
_, s1, p1 = await _seed_post(db, artist_name="A1", slug="a1",
platform="patreon", ext_id="1")
_, s2, p2 = await _seed_post(db, artist_name="A2", slug="a2",
platform="fanbox", ext_id="2")
ip1 = ImageProvenance(image_record_id=rec.id, post_id=p1.id,
source_id=s1.id)
ip2 = ImageProvenance(image_record_id=rec.id, post_id=p2.id,
source_id=s2.id)
db.add(ip1)
await db.flush()
db.add(ip2)
await db.flush()
svc = ProvenanceService(db)
payload = await svc.for_image(rec.id)
ids = [e["provenance_id"] for e in payload["provenance"]]
assert ids == sorted(ids) # captured_at, id ascending → insertion order
assert len(payload["provenance"]) == 2
@pytest.mark.asyncio
async def test_for_image_null_post_fields_serialize_null(db):
rec = await _seed_image(db)
_, source, post = await _seed_post(
db, artist_name="Bob", slug="bob", platform="x", ext_id="9",
) # title/desc/count/post_url default-ish
db.add(ImageProvenance(image_record_id=rec.id, post_id=post.id,
source_id=source.id))
await db.flush()
svc = ProvenanceService(db)
e = (await svc.for_image(rec.id))["provenance"][0]
assert e["post"]["title"] is None
assert e["post"]["description_html"] is None
assert e["post"]["attachment_count"] is None
@pytest.mark.asyncio
async def test_for_post_missing_returns_none(db):
svc = ProvenanceService(db)
assert await svc.for_post(999999) is None
@pytest.mark.asyncio
async def test_for_post_returns_post_source_artist(db):
artist, source, post = await _seed_post(
db, artist_name="Carol", slug="carol", platform="patreon",
ext_id="77", title="T", desc="<p>d</p>", count=3,
)
svc = ProvenanceService(db)
payload = await svc.for_post(post.id)
assert payload["post"]["id"] == post.id
assert payload["post"]["title"] == "T"
assert payload["post"]["description_html"] == "<p>d</p>"
assert payload["post"]["attachment_count"] == 3
assert payload["source"] == {"id": source.id, "platform": "patreon",
"url": source.url}
assert payload["artist"] == {"id": artist.id, "name": "Carol",
"slug": "carol"}
@pytest.mark.asyncio
async def test_for_post_includes_attachments(db):
artist, source, post = await _seed_post(
db, artist_name="Att", slug="att", platform="patreon",
ext_id="55",
)
db.add(PostAttachment(
post_id=post.id, artist_id=artist.id, sha256="t" + "0" * 63,
path="/images/attachments/t00/t.zip", original_filename="t.zip",
ext=".zip", mime="application/zip", size_bytes=9,
))
await db.flush()
svc = ProvenanceService(db)
payload = await svc.for_post(post.id)
assert len(payload["attachments"]) == 1
att = payload["attachments"][0]
assert att["original_filename"] == "t.zip"
assert att["download_url"].endswith(
f"/api/attachments/{att['id']}/download"
)