Skip to content

bug: _migrate_sync_health race condition between uvicorn workers #456

Closed

Description

@vybe

Summary

_migrate_sync_health (introduced in #389) uses a check-then-act pattern (PRAGMA table_info followed by ALTER TABLE ADD COLUMN) that is not atomic under concurrent execution. When the backend starts with multiple uvicorn workers (default is --workers 2), both workers run run_all_migrations() on startup and race: worker A's PRAGMA returns no column, worker A ALTERs successfully, worker B's PRAGMA also returned no column (before A committed), worker B ALTERs and hits duplicate column name: auto_sync_enabled. The losing worker crashes during startup.

End-state is correct (column exists, worker respawns and finds it present), so this is not a data or functionality bug — but every cold start logs a scary traceback and Child process [N] died, which will train operators to ignore real migration failures.

Component

Backend / Migrations

Priority

P2 — feature impaired (migration fails on one worker), workaround is "ignore the traceback, column ends up present."

Error

Migration FAILED (sync_health): duplicate column name: auto_sync_enabled
Traceback (most recent call last):
  File \"/app/db/migrations.py\", line 80, in run_all_migrations
    migration_fn(cursor, conn)
  File \"/app/db/migrations.py\", line 1404, in _migrate_sync_health
    cursor.execute(
sqlite3.OperationalError: duplicate column name: auto_sync_enabled
INFO:     Child process [8] died

Location

  • File: src/backend/db/migrations.py
  • Line: ~1404 (inside _migrate_sync_health)
  • Function: _migrate_sync_health
  • Docstring claim: "Idempotent: guards every change with PRAGMA table_info / table-existence checks." — idempotent single-threaded, but not concurrent-safe.

The same pattern is used for the second ALTER (freeze_schedules_if_sync_failing) and the CREATE TABLE agent_sync_state block in the same function, and likely in other migrations that add columns. Fix should be applied systemically.

Reproduction Steps

  1. Fresh deploy of a commit that includes Sync health observability (S1) #389 (base image + backend rebuild) against a DB that does not yet have agent_git_config.auto_sync_enabled.
  2. Start backend with --workers 2 or more (this is the default production config).
  3. Observe the backend logs: one worker prints Adding auto_sync_enabled column to agent_git_config for auto-sync cadence (#389)..., the other worker prints Migration FAILED (sync_health): duplicate column name: auto_sync_enabled and its child process dies.
  4. After the losing worker respawns, the column exists, PRAGMA check passes, and subsequent startups are clean — until the next migration adds a new column and the race repeats.

Root Cause

run_all_migrations() is called per-worker (via FastAPI lifespan or module-level init, I assume). SQLite ALTER TABLE ADD COLUMN is DDL and commits immediately, but the PRAGMA table_info result is cached per-connection and not protected by a transaction against other connections. Two workers starting simultaneously each see the pre-migration schema, both decide to ALTER, and one loses.

Suggested Fix

Two options, not mutually exclusive:

Option 1 (smallest, least invasive): wrap the ALTER/CREATE calls in try/except sqlite3.OperationalError and treat "duplicate column" / "table already exists" as success:

def _safe_add_column(cursor, table, column, ddl):
    cursor.execute(f\"PRAGMA table_info({table})\")
    if column in {row[1] for row in cursor.fetchall()}:
        return
    try:
        cursor.execute(ddl)
    except sqlite3.OperationalError as e:
        if \"duplicate column name\" in str(e).lower():
            return  # another worker won the race
        raise

Apply to every ALTER TABLE ADD COLUMN in migrations.py. Similar pattern for CREATE TABLE via CREATE TABLE IF NOT EXISTS (which SQLite already supports atomically).

Option 2 (architecturally correct): run migrations in a separate process before uvicorn forks workers. For example, a Docker ENTRYPOINT step like:

python -m db.migrate && exec uvicorn main:app ...

This guarantees single-writer semantics and also surfaces real migration failures as non-zero exit codes instead of worker respawn loops.

Option 1 alone is enough to silence the log noise; Option 2 is the durable fix.

Environment

Related

Activity

  1. added
    status-in-progress
    and removed on Apr 27, 2026
  2. self-assigned this
    on Apr 27, 2026
  3. added
    status-in-dev
    and removed
    status-in-progress
    on Apr 28, 2026
  4. added a commit that references this issue on Apr 30, 2026
  5. vybe commented on Jun 1, 2026

    @vybe
    ContributorAuthor

    Shipped in v0.6.0 (released via #998).

  6. added
    complexity-low
    theme-reliability
    and removed
    status-in-dev
    on Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

complexity-lowpriority-p2theme-reliabilitytype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions