close
Skip to content

Fix UNIQUE constraint crash when same --attachment passed twice#1417

Open
abhicris wants to merge 1 commit intosimonw:mainfrom
abhicris:fix-prompt-attachments-pk
Open

Fix UNIQUE constraint crash when same --attachment passed twice#1417
abhicris wants to merge 1 commit intosimonw:mainfrom
abhicris:fix-prompt-attachments-pk

Conversation

@abhicris
Copy link
Copy Markdown

Closes #1354.

The bug

$ llm "Describe this" --attachment resume.pdf --attachment resume.pdf
...
File ".../llm/models.py", line 924, in log_to_db
    db["prompt_attachments"].insert(...)
sqlite3.IntegrityError: UNIQUE constraint failed:
  prompt_attachments.response_id, prompt_attachments.attachment_id

The prompt_attachments table was created in m012 with a composite PK of (response_id, attachment_id), so inserting the same attachment a second time against one response violates the constraint. The full prompt + model call runs fine; only the log step crashes, which means the user sees a traceback instead of output.

The fix

This is the same bug that previously existed on prompt_fragments, fixed in m016_fragments_table_pks by extending the PK with the per-row order column. This PR mirrors that fix with a new migration:

@migration
def m022_prompt_attachments_pk(db):
    db["prompt_attachments"].transform(
        pk=("response_id", "attachment_id", "order")
    )

log_to_db() already passes a distinct order per attachment (enumerate(self.prompt.attachments)), so the logic side needs no change.

Verification

  • Reproduced the IntegrityError against main at 1bfb96d.
  • After the migration, both fresh databases and databases upgraded from pre-m022 schema accept duplicate (response_id, attachment_id) rows with distinct order.
  • Added test_duplicate_attachment_logs_cleanly in tests/test_attachments.py exercising the CLI path end-to-end.
  • Full test suite green (457 passed) excluding the existing openai-models + async-recording tests that require network/cassettes.

--- kcolbchain / Abhishek Krishna

`llm "..." --attachment file.pdf --attachment file.pdf` raised
`sqlite3.IntegrityError: UNIQUE constraint failed:
prompt_attachments.response_id, prompt_attachments.attachment_id`
from `_BaseResponse.log_to_db()` because the composite primary key on
`prompt_attachments` was `(response_id, attachment_id)`.

The same issue existed historically on `prompt_fragments` and was
fixed in migration m016 by extending the PK with the `order` column.
This mirrors that fix for `prompt_attachments` via a new
`m022_prompt_attachments_pk` migration, and adds a CLI-level
regression test.

Closes simonw#1354
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unhandled sqlite unique constraint violation when --attachment is passed twice on the same file

1 participant