birdnetlib developer on retainer: SQLAlchemy Column(Integer) truncates confidence float to 0 — dashboard filter confidence ≥ 0.5 returns zero detections — app shows no birds detected — 3 000 recordings per month — 3 weeks — birdnetlib developer on monthly retainer

birdnetlib 0.9.0 • Python 3.9 • SQLAlchemy 1.4 • PostgreSQL 14; recording.detections returns confidence float in [0.0, 1.0]; Column(Integer) calls int(0.73)=0 on INSERT; all 47,000 detections stored with confidence=0; no rows match WHERE confidence ≥ 0.5 • Southfield Birdnetlib Ltd. (wildlife monitoring; 50 nature reserves; 150 bird species; 3,000 recordings/month; app shows zero detections; 3 weeks; fix: Column(Float); 1.5h retainer engagement)

Southfield Birdnetlib Ltd. built an automated wildlife monitoring service that ran birdnetlib 0.9.0 on recordings from 50 nature reserves to detect and track 150 target bird species — 3,000 field recordings per month submitted by reserve staff via a web upload portal. The service stored each birdnetlib detection in a PostgreSQL database and displayed species counts, detection confidence scores, and temporal trends on a reserve-facing dashboard. Nature reserve partners reported that after the first full month of operation, the dashboard showed zero detections across all 50 reserves — not a single bird species identified. The service appeared to be entirely non-functional.

birdnetlib 0.9.0 Recording(analyzer=analyzer, path=audio_path, lat=lat, lon=lon, date=date_obj, min_conf=0.25) followed by recording.analyze() populates recording.detections with a list of Python dicts. Each dict contains: 'common_name' (str, e.g. 'House Finch'), 'scientific_name' (str, e.g. 'Haemorhous mexicanus'), 'start_time' (float, seconds from start of recording), 'end_time' (float, seconds), and 'confidence' (float, range 0.0 to 1.0). The developer had defined the SQLAlchemy ORM model for the detection table with confidence = Column(Integer, nullable=False, default=0). When a detection was inserted via session.add(Detection(confidence=det['confidence'])), SQLAlchemy’s Integer type adapter called Python’s int() built-in on the value before constructing the SQL INSERT statement. int(0.73) = 0. int(0.45) = 0. int(0.99) = 0. Every detection — regardless of actual BirdNET confidence — was stored with confidence = 0. The INSERT succeeded without error, the commit completed, and the application logged no exceptions.

The annotated buggy and fixed SQLAlchemy Detection model and insertion code, with startup validation:

# Southfield Birdnetlib Ltd. — birdnetlib 0.9.0 Column(Integer) confidence fix
# birdnetlib 0.9.0; Python 3.9; SQLAlchemy 1.4; PostgreSQL 14
# Wildlife monitoring; 50 reserves; 150 species; 3,000 recordings/month
#
# Problem: recording.detections[i]['confidence'] is a Python float in [0.0, 1.0]
#          SQLAlchemy Column(Integer) calls int(float) before INSERT
#          int(0.73) = 0; int(0.45) = 0; int(0.99) = 0
#          All 47,000 detections stored with confidence=0
#          Dashboard WHERE confidence >= 0.5 returns 0 rows
#          App shows zero detections across all 50 nature reserves
# Fix:     Column(Float) stores the value as-is; no int() coercion

from datetime import date
from sqlalchemy import Column, Integer, Float, String, create_engine
from sqlalchemy.orm import declarative_base, Session
from birdnetlib import Recording
from birdnetlib.analyzer import Analyzer

Base = declarative_base()


# ── BUGGY Detection model ─────────────────────────────────────────────────────

class DetectionBuggy(Base):
    __tablename__ = 'detections_buggy'
    id              = Column(Integer, primary_key=True)
    common_name     = Column(String)
    scientific_name = Column(String)
    start_time      = Column(Float)
    end_time        = Column(Float)
    # BUG: Column(Integer) calls int() on the value before INSERT
    # int(0.73) = 0; int(0.45) = 0; int(0.99) = 0
    # All confidence values stored as 0; no detection passes threshold filter
    confidence      = Column(Integer, nullable=False, default=0)


# ── FIXED Detection model ─────────────────────────────────────────────────────

class Detection(Base):
    __tablename__ = 'detections'
    id              = Column(Integer, primary_key=True)
    common_name     = Column(String)
    scientific_name = Column(String)
    start_time      = Column(Float)
    end_time        = Column(Float)
    # FIX: Column(Float) stores the value without coercion
    # 0.73 stored as 0.73; WHERE confidence >= 0.5 returns correct rows
    confidence      = Column(Float, nullable=False)


# ── Detection insertion ───────────────────────────────────────────────────────

def store_detections(session: Session, recording: Recording) -> int:
    """Insert birdnetlib detections into the database. Returns count inserted."""
    inserted = 0
    for det in recording.detections:
        # Validate confidence range before insert
        conf = det['confidence']
        if not isinstance(conf, float):
            raise TypeError(
                f"birdnetlib detection confidence expected float, got "
                f"{type(conf).__name__}: {conf!r}. "
                "Check birdnetlib API version — confidence should be float in [0.0, 1.0]."
            )
        if not (0.0 <= conf <= 1.0):
            raise ValueError(
                f"birdnetlib detection confidence {conf} outside [0.0, 1.0]. "
                "Unexpected birdnetlib output format."
            )
        session.add(Detection(
            common_name=det['common_name'],
            scientific_name=det['scientific_name'],
            start_time=det['start_time'],
            end_time=det['end_time'],
            confidence=conf,  # float stored as-is with Column(Float)
        ))
        inserted += 1
    return inserted


# ── Startup schema validation ─────────────────────────────────────────────────

def validate_confidence_schema(engine) -> None:
    """Assert Column(Float) stores confidence correctly — catches Column(Integer) regressions."""
    with Session(engine) as session:
        test_det = Detection(
            common_name='_test_',
            scientific_name='_test_',
            start_time=0.0,
            end_time=3.0,
            confidence=0.73,
        )
        session.add(test_det)
        session.flush()
        retrieved = session.get(Detection, test_det.id)
        stored_confidence = retrieved.confidence
        session.rollback()

    if stored_confidence != 0.73:
        raise RuntimeError(
            f"Schema validation failed: inserted confidence=0.73, "
            f"retrieved confidence={stored_confidence}. "
            "If stored value is 0, the column type is INTEGER (truncates floats). "
            "Fix: change Column(Integer) to Column(Float) and run alembic migration."
        )

How SQLAlchemy’s silent int() coercion on Column(Integer), a successful INSERT with no exceptions, and a dashboard filter that always returns zero rows combine to produce three weeks of undetected precision loss — and the correct Column(Float) pattern for birdnetlib confidence storage

The core failure combines three independent factors: SQLAlchemy’s Integer type adapter silently applies Python’s int() to any value before constructing the INSERT, with no warning, exception, or log entry about precision loss; the database INSERT succeeds with confidence=0 because zero is a valid integer; and the application-level validation — which checked that recording.analyze() ran without error and that session.commit() succeeded — never verified what was actually stored. The developer debugged by inspecting the Python-side detection objects (print(recording.detections) showed correct confidence values), confirming BirdNET inference was working, and never queried the database directly to verify the stored values matched. The correct fix is Column(Float), which stores the value as a double-precision float without any coercion. The recovery required: an Alembic migration to change the column type from INTEGER to FLOAT; a backfill script that re-ran recording.analyze() on all 3,000 recordings from the prior month and re-inserted detections with correct confidence values; and a startup schema validation that inserts a test detection with confidence=0.73, reads it back, and asserts the retrieved value equals 0.73 (not 0). The retainer engagement was 1.5h: 0.5h triage (direct recording.detections print showed correct floats; SELECT confidence FROM detections LIMIT 10 showed all zeros; schema inspection showed Column(Integer)); 0.25h root cause (SQLAlchemy Integer adapter calls int(); int(0.73)=0; fix: Column(Float)); 0.5h fix (Alembic migration; backfill script for 3,000 prior recordings; startup validation); 0.25h validation (100-recording test; confidence values stored correctly as floats; dashboard filter returns correct species counts per reserve; 1.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →