Microsoft.Data.Sqlite: BeginTransaction(deferred: false) sometimes throws "cannot start a transaction within a transaction" under contention and leaves the transaction open
Bug description
Under write contention on Linux, SqliteConnection.BeginTransaction(deferred: false) occasionally throws SQLite Error 1: 'cannot start a transaction within a transaction', and when it does, the connection is left with a native transaction open (sqlite3_get_autocommit returns 0) that no SqliteTransaction owns. With pooling on, that connection then goes back to the pool in that state.
I think this comes from the busy handling in SqliteDataReader.NextResult: when sqlite3_step returns BUSY it calls sqlite3_reset, sleeps 150 ms and steps the same statement again. For BEGIN IMMEDIATE that seems to be unsafe. If the first step already took effect but still reported BUSY, the second step runs BEGIN IMMEDIATE on a connection that is already inside a transaction, and SQLite rejects it. BeginTransaction throws, but nothing rolls back the transaction the first step opened.
Rate in my runs is roughly 1 in 1,000 to 2,500 BEGINs. In one run of 9,600 BEGINs I got 4 failures, all inside BeginTransaction:
- 3 ×
'cannot start a transaction within a transaction', each leaving autocommit = 0 on the connection afterwards - 1 ×
'SQL logic error'(I have also seen rc 1 with the message'not an error')
sqlite3_get_autocommit was 1 before every one of those BEGINs, so the connections did not come out of the pool already in a transaction in that run. In another configuration (WAL + PRAGMA busy_timeout) I did once get a pooled connection handed out with autocommit already off, which I'd guess is a connection leaked like this going back to the pool.
I only see it on Linux. On Windows I got 0 in 960 BEGINs, but at this rate that doesn't say much.
#39082 / #39083 looks related: it stops a connection with an unsettled native transaction from being pooled. As far as I can see it doesn't change the BUSY retry, so BeginTransaction would still throw spuriously here. Expected: either the retry is safe for BEGIN (for example, check sqlite3_get_autocommit before stepping again and treat "this command already started the transaction" as success), or a failed BeginTransaction rolls back whatever it opened.
Your code
16 tasks per database file, each one: open a pooled connection, BeginTransaction(deferred: false), PRAGMA table_info, the first one also does ALTER TABLE ... ADD COLUMN, one INSERT, commit. Repeated over 600 database files. It takes about 25 minutes, mostly spent in the library's 150 ms busy sleep.
repro.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.12" />
</ItemGroup>
</Project>
Program.cs:
// Minimal repro for: BEGIN IMMEDIATE under contention fails inside BeginTransaction on Linux.
// N tasks per round, each: open (pooled) -> log autocommit -> BeginTransaction(deferred:false) -> PRAGMA table_info + one write -> commit -> close.
// Usage: dotnet run -c Release -- <tasks> <rounds> <pooling:true|false> <mode:write|alter>
using Microsoft.Data.Sqlite;
using System.Collections.Concurrent;
int tasks = args.Length > 0 ? int.Parse(args[0]) : 16;
int rounds = args.Length > 1 ? int.Parse(args[1]) : 200;
bool pooling = args.Length > 2 ? bool.Parse(args[2]) : true;
string mode = args.Length > 3 ? args[3] : "alter";
int busyTimeoutMs = args.Length > 4 ? int.Parse(args[4]) : 0;
bool wal = args.Length > 5 && bool.Parse(args[5]); // >0: SQLite's own busy handler waits, so the library never resets and re-steps a BUSY BEGIN
var dir = Path.Combine(Path.GetTempPath(), "sqlite-repro-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
var errors = new ConcurrentDictionary<string, int>();
int notAutocommitBeforeBegin = 0;
int ok = 0;
var sw = System.Diagnostics.Stopwatch.StartNew();
using (var c0 = new SqliteConnection("Data Source=:memory:")) c0.Open(); // Microsoft.Data.Sqlite sets the provider on first open
Console.WriteLine($"OS={System.Runtime.InteropServices.RuntimeInformation.OSDescription} sqlite={SQLitePCL.raw.sqlite3_libversion().utf8_to_string()} " +
$"tasks={tasks} rounds={rounds} pooling={pooling} mode={mode} busyTimeoutMs={busyTimeoutMs} wal={wal}");
for (int r = 0; r < rounds; r++)
{
var db = Path.Combine(dir, $"r{r}.db");
var cs = new SqliteConnectionStringBuilder { DataSource = db, Pooling = pooling, DefaultTimeout = 30 }.ToString();
using (var init = new SqliteConnection(cs))
{
init.Open();
using var c = init.CreateCommand();
c.CommandText = (wal ? "PRAGMA journal_mode=WAL; " : "") + "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, a TEXT)";
c.ExecuteNonQuery();
}
var work = Enumerable.Range(0, tasks).Select(i => Task.Run(() =>
{
using var conn = new SqliteConnection(cs);
var stage = "open";
try
{
conn.Open();
if (busyTimeoutMs > 0) { using var bt = conn.CreateCommand(); bt.CommandText = $"PRAGMA busy_timeout={busyTimeoutMs}"; bt.ExecuteNonQuery(); }
if (SQLitePCL.raw.sqlite3_get_autocommit(conn.Handle) == 0) Interlocked.Increment(ref notAutocommitBeforeBegin);
stage = "begin";
using var tx = conn.BeginTransaction(deferred: false);
stage = "body";
using (var q = conn.CreateCommand())
{
q.Transaction = tx;
q.CommandText = "PRAGMA table_info(t)";
var cols = new List<string>();
using (var rd = q.ExecuteReader()) while (rd.Read()) cols.Add(rd.GetString(1));
if (mode == "alter" && !cols.Contains("b"))
{
q.CommandText = "ALTER TABLE t ADD COLUMN b TEXT";
q.ExecuteNonQuery();
}
q.CommandText = "INSERT INTO t (a) VALUES ($a)";
q.Parameters.AddWithValue("$a", $"r{r}-{i}");
q.ExecuteNonQuery();
}
tx.Commit();
Interlocked.Increment(ref ok);
}
catch (Exception ex)
{
// After the failure: is a native transaction still open on this connection, which no SqliteTransaction owns once
// this scope disposes it (the pool would then hand it out with autocommit off)?
var openAfter = conn.State == System.Data.ConnectionState.Open && SQLitePCL.raw.sqlite3_get_autocommit(conn.Handle) == 0;
var key = $"[{stage}{(openAfter ? ", native tx left open" : "")}] {ex.GetType().Name}: {ex.Message.Split('\n')[0]}";
errors.AddOrUpdate(key, 1, (_, n) => n + 1);
if (errors[key] == 1)
Console.WriteLine($"round {r}: {key}\n" + string.Join("\n", (ex.StackTrace ?? "").Split('\n')
.Where(l => l.Contains("Sqlite") || l.Contains("Program")).Select(l => " " + l.Trim())));
}
})).ToArray();
Task.WaitAll(work);
}
Console.WriteLine($"done in {sw.Elapsed.TotalSeconds:F1}s ok={ok} notAutocommitBeforeBegin={notAutocommitBeforeBegin}");
foreach (var (k, v) in errors.OrderByDescending(e => e.Value)) Console.WriteLine($" {v,5} x {k}");
SqliteConnection.ClearAllPools();
try { Directory.Delete(dir, true); } catch (IOException) { }
return errors.IsEmpty ? 0 : 1;
I ran it in mcr.microsoft.com/dotnet/sdk:10.0 with dotnet run -c Release -- 16 600 true alter.
Stack traces
OS=Ubuntu 24.04.4 LTS sqlite=3.53.4 tasks=16 rounds=600 pooling=True mode=alter busyTimeoutMs=0 wal=False
round 347: [begin, native tx left open] SqliteException: SQLite Error 1: 'cannot start a transaction within a transaction'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Program.<>c__DisplayClass0_2.<<Main>$>b__1() in /w/Program.cs:line 47
round 372: [begin] SqliteException: SQLite Error 1: 'SQL logic error For more information on this error code see https://www.sqlite.org/rescode.html'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Program.<>c__DisplayClass0_2.<<Main>$>b__1() in /w/Program.cs:line 47
done in 1509.4s ok=9596 notAutocommitBeforeBegin=0
3 x [begin, native tx left open] SqliteException: SQLite Error 1: 'cannot start a transaction within a transaction'.
1 x [begin] SqliteException: SQLite Error 1: 'SQL logic error For more information on this error code see https://www.sqlite.org/rescode.html'.
(The program trims the stack to Sqlite and Program frames. Line 47 is the BeginTransaction(deferred: false) call.)
Verbose output
No response
EF Core version
Microsoft.Data.Sqlite 10.0.12 (latest stable). Also reproduces on 11.0.0-rc.1.26425.128 with the same program and its default SQLitePCLRaw bundle: 7 failures in 9,600 BEGINs, 2 × 'cannot start a transaction within a transaction', 2 × 'SQL logic error', 3 × 'not an error', 3 of the 7 leaving the native transaction open. (rc.1 predates #39083, but that PR doesn't touch this path anyway.)
Database provider
Microsoft.Data.Sqlite
Target framework
.NET 10.0
Operating system
Linux (Ubuntu 24.04 in the mcr.microsoft.com/dotnet/sdk:10.0 container), SQLite 3.53.x. Same with the default SQLitePCLRaw bundle (2.1.x) and with SQLitePCLRaw 3.0.5.
IDE
No response
AI Triage
The below is an AI-generated analysis and may contain inaccuracies.
Reproduction results
I could not reproduce this on main. I also could not reproduce it with the reported 10.0.12 driver in this environment, so these results do not establish that main fixes this particular report.
I ran the supplied program's workload (16 600 true alter: 9,600 transactions per run, pooling enabled, no WAL, no native busy timeout), with added assembly-identity output. Main used a Release build of the unchanged checkout at 2c982ae264554eb66a1a045b0d91ed55e34e4fa8; the executed driver DLL matched that build byte-for-byte.
Environment: Ubuntu 24.04.5 x64; SQLitePCLRaw.bundle_e_sqlite3 3.0.5, reporting SQLite 3.53.4, for both drivers. The published-driver project used Microsoft.Data.Sqlite.Core 10.0.12 plus that explicit bundle, rather than the metapackage's default bundle.
| Runtime | Driver | Successful transactions | Exceptions | Autocommit off before BEGIN | Duration |
|---|---|---|---|---|---|
| .NET 10.0.12 | Published 10.0.12 | 9,600 | 0 | 0 | 387.9 s |
| .NET 10.0.12 | Main | 9,600 | 0 | 0 | 409.3 s |
| .NET 11 RC1 | Published 10.0.12 | 9,600 | 0 | 0 | 391.8 s |
| .NET 11 RC1 | Main | 9,600 | 0 | 0 | 432.9 s |
Each run exited successfully. A finite passing stress run cannot exclude this rare race. No independently failing minimal repro or failing-versus-working version comparison was obtained, so regression status remains unconfirmed.
Likely related issues
- #39008 / #39009 is a plausible duplicate, not yet confirmed for this workload. That pool-activation race can give two live
SqliteConnectionobjects the same native handle and cause exactlycannot start a transaction within a transaction. Both 10.0.12 and 11 RC1 retain the old activation ordering; main publishes the owner first. Observing autocommit=1 before each BEGIN does not exclude this race: another owner could begin on the same handle after that check. - #39082 / #39083 addresses the subsequent pooling of an unsettled native transaction. Main contains that protection too. It is distinct from determining why BEGIN failed.
The BUSY/reset/re-step path still exists on main. The reported exception alone does not establish that this retry path is the cause.
The existing Bug type and area-adonet-sqlite label are appropriate. Please retry with 10.0.13, whose ownership fix was backported in #39012, and separately with Pooling=False. If it persists with pooling disabled or the ownership fix present, that would help distinguish a separate BEGIN/BUSY problem from #39008. Logging simultaneously owned native handle addresses would further test the duplicate-ownership hypothesis.
Thanks for the triage. I re-ran the repro from the issue on Linux (mcr.microsoft.com/dotnet/sdk:10.0, Ubuntu 24.04, SQLite 3.53.3 from the package's own SQLitePCLRaw), 16 tasks × 600 rounds, ALTER mode, rollback journal, same container and day:
| Microsoft.Data.Sqlite | Pooling | BEGINs | throws in BeginTransaction | native tx left open |
|---|---|---|---|---|
| 10.0.12 | true | 9,600 | 4 | 1 |
| 10.0.13 | true | 19,200 (two runs) | 0 | 0 |
| 10.0.13 | false | 9,600 | 0 | 0 |
So 10.0.13 fixes it for us. That fits #39008: a connection lent to two owners would explain both "cannot start a transaction within a transaction" and a native transaction left open after the throw. Fine to close from our side — thanks.