Files
FabledCurator/tests/test_migration_0008.py
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

138 lines
3.8 KiB
Python

"""FC-2d-vii-c: image_record.artist_id + backfill + artist-tag delete."""
from datetime import UTC, datetime, timedelta
import pytest
from sqlalchemy import func, select, text
from backend.app.models import (
Artist,
ImageProvenance,
ImageRecord,
Post,
Source,
Tag,
TagKind,
)
from backend.app.models.tag import image_tag
from backend.app.utils.artist_backfill import (
BACKFILL_PRIMARY_SQL,
BACKFILL_PROVENANCE_SQL,
BACKFILL_TAG_SQL,
DELETE_ARTIST_TAGS_SQL,
)
pytestmark = pytest.mark.integration
def test_image_record_has_artist_id_column():
assert "artist_id" in {c.name for c in ImageRecord.__table__.columns}
async def _img(db, n):
rec = ImageRecord(
path=f"/images/bf/{n}.jpg", sha256=f"bf{n:062d}",
size_bytes=1, mime="image/jpeg", width=1, height=1,
origin="imported_filesystem", integrity_status="unknown",
)
rec.created_at = datetime.now(UTC) - timedelta(minutes=n)
db.add(rec)
await db.flush()
return rec
async def _artist_source(db, name, slug):
a = Artist(name=name, slug=slug)
db.add(a)
await db.flush()
s = Source(artist_id=a.id, platform="patreon",
url=f"https://p.test/{slug}")
db.add(s)
await db.flush()
return a, s
async def _run_backfill(db):
await db.execute(text(BACKFILL_PRIMARY_SQL))
await db.execute(text(BACKFILL_PROVENANCE_SQL))
await db.execute(text(BACKFILL_TAG_SQL))
@pytest.mark.asyncio
async def test_backfill_primary_post(db):
rec = await _img(db, 1)
a, s = await _artist_source(db, "Alice", "alice")
post = Post(source_id=s.id, artist_id=a.id, external_post_id="1")
db.add(post)
await db.flush()
rec.primary_post_id = post.id
await db.flush()
await _run_backfill(db)
got = await db.scalar(
select(ImageRecord.artist_id).where(ImageRecord.id == rec.id)
)
assert got == a.id
@pytest.mark.asyncio
async def test_backfill_provenance_fallback(db):
rec = await _img(db, 1)
a, s = await _artist_source(db, "Bob", "bob")
post = Post(source_id=s.id, artist_id=a.id, external_post_id="2")
db.add(post)
await db.flush()
db.add(ImageProvenance(image_record_id=rec.id, post_id=post.id,
source_id=s.id))
await db.flush()
await _run_backfill(db)
got = await db.scalar(
select(ImageRecord.artist_id).where(ImageRecord.id == rec.id)
)
assert got == a.id
@pytest.mark.asyncio
async def test_backfill_artist_tag_by_name(db):
rec = await _img(db, 1)
a = Artist(name="Carol", slug="carol")
db.add(a)
await db.flush()
tag = Tag(name="Carol", kind=TagKind.artist)
db.add(tag)
await db.flush()
await db.execute(image_tag.insert().values(
image_record_id=rec.id, tag_id=tag.id, source="auto"))
await db.flush()
await _run_backfill(db)
got = await db.scalar(
select(ImageRecord.artist_id).where(ImageRecord.id == rec.id)
)
assert got == a.id
@pytest.mark.asyncio
async def test_no_signal_stays_null(db):
rec = await _img(db, 1)
await _run_backfill(db)
got = await db.scalar(
select(ImageRecord.artist_id).where(ImageRecord.id == rec.id)
)
assert got is None
@pytest.mark.asyncio
async def test_delete_removes_only_artist_tags(db):
artist_tag = Tag(name="Dave", kind=TagKind.artist)
general_tag = Tag(name="forest", kind=TagKind.general)
db.add_all([artist_tag, general_tag])
await db.flush()
await db.execute(text(DELETE_ARTIST_TAGS_SQL))
remaining = await db.scalar(
select(func.count()).select_from(Tag).where(Tag.kind == TagKind.artist)
)
assert remaining == 0
survived = await db.scalar(
select(func.count()).select_from(Tag).where(Tag.kind == TagKind.general)
)
assert survived >= 1