INSERT OR REPLACE causes UNIQUE constraint failure on vec table primary key
Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 1: 'UNIQUE constraint failed on vec_comments primary key'.'
private int UpsertEmbeddings(string tableName, IEnumerable<VectorEmbedding> vectorEmbeddings)
{
var affectedRows = 0;
using var transaction = connection.BeginTransaction();
using var command = connection.CreateCommand();
command.CommandText = $"INSERT OR REPLACE INTO {tableName} (rowid, embedding) Values (@id, @embedding);";
command.Parameters.Add("@id", SqliteType.Integer);
command.Parameters.Add("@embedding", SqliteType.Blob);
foreach (var embedding in vectorEmbeddings)
{
command.Parameters["@id"].Value = embedding.Id;
command.Parameters["@embedding"].Value = MapVectorToBytes(embedding.Embedding);
affectedRows += command.ExecuteNonQuery();
}
transaction.Commit();
return affectedRows;
}
Adding production context to this issue.
We have 9 vec0 virtual tables in production (pattern embeddings, observation embeddings, conversation embeddings, knowledge atoms, etc.) with ~15,000+ total vectors across FLOAT[384] dimensions.
Because INSERT OR REPLACE fails, we use a DELETE-then-INSERT workaround for every vector upsert:
db.prepare('DELETE FROM vec_table WHERE id = ?').run(id)
db.prepare('INSERT INTO vec_table (id, embedding) VALUES (?, ?)').run(id, embedding)
This works but has two consequences:
- Non-atomic — if the process crashes between DELETE and INSERT, the vector is lost
- Wasted space — per issue #54, DELETE only sets a validity bit without reclaiming storage. Our database grows monotonically with every re-embedding
This is the single most impactful missing feature for production vec0 usage. Every application that updates embeddings (which is nearly all of them) hits this.
— Murillo Dutt
Thanks, @murillodutt. I considered the same approach and decided to use the non-virtual table instead, as my requirements are simple and don’t require KNN.
This appears fixed on main by b95c05b ("Support INSERT OR REPLACE for vec0 virtual tables"), which closed #127 — the same underlying gap, reported from a different binding.
Replaying the pattern from your UpsertEmbeddings (repeated INSERT OR REPLACE INTO ... (rowid, embedding) VALUES (?, ?) over the same rowids, inside a transaction) against v0.1.10-alpha.4:
iteration 0: OK, rows=3
iteration 1: OK, rows=3
iteration 2: OK, rows=3
final: [(1, '[3,3,3,3]'), (2, '[4,4,4,4]'), (3, '[5,5,5,5]')]
No UNIQUE constraint failed — rows are replaced in place and the vectors reflect the last write.
Note this landed after 0.1.9, so it needs v0.1.10-alpha.2 or later. Given the .NET packaging discussion in #193, the fixed build may not be reachable through Microsoft.Data.Sqlite yet, which could be why this still looks broken from where you sit.