Commit 77eff0b8 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix upload 500: index sha256(fingerprint) instead of the raw fingerprint

Real uploads were failing with a 500 on prod's Postgres - "index row
size 3184 exceeds btree version 4 maximum 2704" on both
ix_library_songs_fingerprint and the IdentifiedTrack cache's unique
index. A Chromaprint fingerprint for a long/complex track can run
several KB, well past Postgres's btree row-size limit; SQLite never
enforces that, so every local/dev upload worked fine until a real one
hit Postgres. Dedup/cache lookups now filter on a new fingerprint_hash
column (sha256, fixed 64 hex chars) instead - fingerprint itself stays
on the row as unindexed reference data. Migration backfills existing
rows in Python so it runs correctly against both SQLite and Postgres.
parent 73e00a51
Pipeline #1292 failed with stage
"""use sha256 fingerprint_hash for indexing instead of raw fingerprint
Revision ID: 20a199643cc2
Revises: 0323f5b7b4a9
Create Date: 2026-11-23 13:33:35.949008
A raw Chromaprint fingerprint can run several KB for a long/complex track, which exceeds
Postgres's btree row-size limit the moment it's indexed directly - confirmed live on prod:
"index row size 3184 exceeds btree version 4 maximum 2704 for index
ix_library_songs_fingerprint" (and the identical error on the IdentifiedTrack cache write,
which used the same pattern as a unique index). SQLite never enforces this limit, which is
why every local/dev upload worked fine right up until a real one hit Postgres.
Fix: index/enforce uniqueness on sha256(fingerprint) instead - fixed-length (64 hex chars),
nowhere near the limit. `fingerprint` itself stays on the row as unindexed reference data.
Backfilled in Python (not a DB-side hash function) so this one migration file runs correctly
against both SQLite (dev) and Postgres (prod).
"""
import hashlib
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '20a199643cc2'
down_revision: Union[str, Sequence[str], None] = '0323f5b7b4a9'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def _backfill(conn, table: str) -> None:
rows = conn.execute(sa.text(f"SELECT id, fingerprint FROM {table} WHERE fingerprint IS NOT NULL")).fetchall()
for row in rows:
digest = hashlib.sha256(row.fingerprint.encode()).hexdigest()
conn.execute(sa.text(f"UPDATE {table} SET fingerprint_hash = :h WHERE id = :id"), {"h": digest, "id": row.id})
def upgrade() -> None:
conn = op.get_bind()
op.add_column('identified_tracks', sa.Column('fingerprint_hash', sa.String(length=64), nullable=True))
op.add_column('library_songs', sa.Column('fingerprint_hash', sa.String(length=64), nullable=True))
_backfill(conn, 'identified_tracks')
_backfill(conn, 'library_songs')
op.drop_index(op.f('ix_identified_tracks_fingerprint'), table_name='identified_tracks')
# batch_alter_table, not a plain op.alter_column - SQLite has no ALTER COLUMN ... SET NOT
# NULL at all (it rebuilds the table under the hood instead); Postgres runs the direct form.
with op.batch_alter_table('identified_tracks') as batch_op:
batch_op.alter_column('fingerprint_hash', existing_type=sa.String(length=64), nullable=False)
op.create_index(op.f('ix_identified_tracks_fingerprint_hash'), 'identified_tracks', ['fingerprint_hash'], unique=True)
op.drop_index(op.f('ix_library_songs_fingerprint'), table_name='library_songs')
op.create_index(op.f('ix_library_songs_fingerprint_hash'), 'library_songs', ['fingerprint_hash'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_library_songs_fingerprint_hash'), table_name='library_songs')
op.create_index(op.f('ix_library_songs_fingerprint'), 'library_songs', ['fingerprint'], unique=False)
op.drop_column('library_songs', 'fingerprint_hash')
op.drop_index(op.f('ix_identified_tracks_fingerprint_hash'), table_name='identified_tracks')
op.create_index(op.f('ix_identified_tracks_fingerprint'), 'identified_tracks', ['fingerprint'], unique=True)
op.drop_column('identified_tracks', 'fingerprint_hash')
......@@ -17,6 +17,7 @@ from src.services.audio_processing import AudioDecodeError, probe_duration_secon
from src.services.music_identification import (
compute_fingerprint,
fetch_lyrics,
fingerprint_hash,
identify_audio,
identify_with_gemini,
)
......@@ -61,12 +62,13 @@ async def _identify_tag_and_store(
metadata.library_song_id (same fix already applied to remix's result files)."""
try:
fingerprint = await compute_fingerprint(raw_file_path)
fp_hash = fingerprint_hash(fingerprint) if fingerprint else None
existing_song = (
db.query(LibrarySong)
.filter(LibrarySong.user_id == current_user.id, LibrarySong.fingerprint == fingerprint)
.filter(LibrarySong.user_id == current_user.id, LibrarySong.fingerprint_hash == fp_hash)
.first()
if fingerprint else None
if fp_hash else None
)
if existing_song:
# Same user, same recording (by content fingerprint, not just title/artist text) -
......@@ -92,8 +94,8 @@ async def _identify_tag_and_store(
}
cached = (
db.query(IdentifiedTrack).filter(IdentifiedTrack.fingerprint == fingerprint).first()
if fingerprint else None
db.query(IdentifiedTrack).filter(IdentifiedTrack.fingerprint_hash == fp_hash).first()
if fp_hash else None
)
if cached:
......@@ -157,6 +159,7 @@ async def _identify_tag_and_store(
if fingerprint:
db.add(IdentifiedTrack(
fingerprint=fingerprint,
fingerprint_hash=fp_hash,
title=candidate.get('title', 'Unknown'),
artist=candidate.get('artist', 'Unknown'),
album=candidate.get('album', ''),
......@@ -195,6 +198,7 @@ async def _identify_tag_and_store(
track_number=candidate.get('track_number'),
file_path=final_path,
fingerprint=fingerprint,
fingerprint_hash=fp_hash,
duration_seconds=probe_duration_seconds(final_path),
confidence=candidate.get('confidence'),
)
......
......@@ -143,8 +143,16 @@ class LibrarySong(Base):
file_path = Column(String)
# Same content fingerprint used to key IdentifiedTrack - lets us detect "this user already
# has this exact recording" before re-tagging and re-storing it, independent of title/
# artist text matching (which is unreliable across correction passes).
fingerprint = Column(String, index=True, nullable=True)
# artist text matching (which is unreliable across correction passes). Not indexed itself -
# see fingerprint_hash below.
fingerprint = Column(String, nullable=True)
# sha256(fingerprint), fixed-length - the real Chromaprint fingerprint this is derived from
# can be several KB for a long/complex track, which blew past Postgres's btree row-size
# limit the moment a real upload hit it in production ("index row size 3184 exceeds btree
# version 4 maximum 2704") - SQLite never enforces that limit, so this went unnoticed
# through every local/dev test. This hash is what dedup lookups actually filter on now;
# `fingerprint` above stays as unindexed raw data, kept for reference only.
fingerprint_hash = Column(String(64), index=True, nullable=True)
# Nullable - no sensible constant default exists per-row. Populated going forward at
# tag/upload/claim/remix time (probe_duration_seconds, audio_processing.py); pre-existing
# rows are lazily backfilled on first read by Radio's own now-playing computation, the
......@@ -377,7 +385,11 @@ class IdentifiedTrack(Base):
Shazam/AcoustID/Gemini/lyrics/genre lookups entirely on the next upload of that audio."""
__tablename__ = "identified_tracks"
id = Column(Integer, primary_key=True, index=True)
fingerprint = Column(String, unique=True, index=True, nullable=False)
# Not indexed itself - see fingerprint_hash below.
fingerprint = Column(String, nullable=False)
# sha256(fingerprint) - see LibrarySong.fingerprint_hash for why this exists. This is what
# the cache lookup/uniqueness constraint actually runs on now.
fingerprint_hash = Column(String(64), unique=True, index=True, nullable=False)
title = Column(String)
artist = Column(String)
album = Column(String)
......
import asyncio
import hashlib
import re
import acoustid
import aiohttp
......@@ -15,6 +16,16 @@ if GEMINI_API_KEY:
musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com")
def fingerprint_hash(fingerprint: str) -> str:
"""Fixed-length (64 hex chars) digest of a raw Chromaprint fingerprint - what dedup/cache
lookups actually filter and index on now, not the fingerprint itself. The real fingerprint
can run several KB for a long/complex track, which exceeds Postgres's btree row-size limit
the moment it's indexed directly ("index row size 3184 exceeds btree version 4 maximum
2704") - SQLite never enforces that, so this went unnoticed until a real upload hit it on
prod's Postgres."""
return hashlib.sha256(fingerprint.encode()).hexdigest()
async def _fetch_cover_art_archive_url(release_id: str) -> str | None:
"""AcoustID/MusicBrainz identify a recording, not artwork - Cover Art Archive (run by the
Internet Archive, keyed by the same release MBID) is the standard companion source for the
......
......@@ -61,6 +61,7 @@ def give_from_shared_library(db: Session, current_user: User, title: str, artist
synced_lyrics=source_song.synced_lyrics,
file_path=source_song.file_path,
fingerprint=source_song.fingerprint,
fingerprint_hash=source_song.fingerprint_hash,
duration_seconds=source_song.duration_seconds,
)
db.add(given)
......
from src.core.database import IdentifiedTrack, LibrarySong
from src.services.music_identification import fingerprint_hash
FAKE_CANDIDATE = {
"title": "Test Title",
......@@ -239,6 +240,7 @@ def test_music_upload_cached_fingerprint_skips_identification(client, db_session
fingerprint = "fp-already-known-xyz789"
db_session.add(IdentifiedTrack(
fingerprint=fingerprint,
fingerprint_hash=fingerprint_hash(fingerprint),
title="Cached Title",
artist="Cached Artist",
album="Cached Album",
......@@ -284,6 +286,7 @@ def test_music_upload_already_in_library_reuses_existing_song(client, db_session
lyrics="existing lyrics",
file_path="./var/storage/downloads/1/existing.mp3",
fingerprint=fingerprint,
fingerprint_hash=fingerprint_hash(fingerprint),
)
db_session.add(existing)
db_session.commit()
......
import asyncio
from src.services.music_identification import fetch_lyrics, identify_audio, parse_lrc
from src.services.music_identification import fetch_lyrics, fingerprint_hash, identify_audio, parse_lrc
def test_fingerprint_hash_is_fixed_length_regardless_of_input_size():
# Regression: indexing the raw Chromaprint fingerprint directly broke real uploads on
# Postgres ("index row size 3184 exceeds btree version 4 maximum 2704") - a long/complex
# track's fingerprint can run several KB, which SQLite never enforced a limit on but
# Postgres's btree does. fingerprint_hash is what's actually indexed now; it must stay a
# fixed 64 hex chars no matter how large the input fingerprint is.
short = fingerprint_hash("AQAD")
long_fp = fingerprint_hash("AQAD" * 2000) # ~8KB, comparable to a real long track
assert len(short) == 64
assert len(long_fp) == 64
def test_fingerprint_hash_is_deterministic_and_input_sensitive():
assert fingerprint_hash("same-input") == fingerprint_hash("same-input")
assert fingerprint_hash("input-a") != fingerprint_hash("input-b")
def test_parse_lrc_basic_lines():
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment