From 2a0a399b18c11771596f9a32b58a1c9b363d7ba9 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 9 Oct 2026 18:36:49 -0500 Subject: [PATCH 01/25] fix: gather full planner statistics instead of sampled ones Sampled ANALYZE (analysis_limit = 400) on connect, disconnect and after CreateIndex read only the first ~400 entries of each index. The general (FullTypeName, Partition) index is ordered by type name, so its sample saw only the smallest types and credited every type with a handful of rows, while the sample of a per-type partial index sat inside one key and credited every key with hundreds. The planner then preferred the general index and parsed every row of the type on each lookup: 82-366 ms per lookup on a 1.68M-row store, against 0-1 ms with full statistics. Results were correct throughout. CreateIndex now runs a full ANALYZE, and connect/disconnect run PRAGMA optimize(0x10002), SQLite's form for long-lived connections, which leaves out the temporary analysis limit the default mask applies. --- CHANGELOG.md | 24 ++ README.md | 7 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 360 ++++++++++++++++++++ TychoDB/Queries.cs | 15 +- TychoDB/Tycho.cs | 27 +- 5 files changed, 419 insertions(+), 14 deletions(-) create mode 100644 TychoDB.UnitTests/PlannerStatisticsTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 117fd5d..9cb4122 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 5.3.2 (unreleased) + +### Fixed + +- **Indexed lookups on a large type read and parsed every row of the type, because + planner statistics were sampled.** The `PRAGMA optimize` run on connect and disconnect + and the `ANALYZE` run after `CreateIndex` set `analysis_limit = 400`, so SQLite read only + the first ~400 entries of each index. The general `(FullTypeName, Partition)` index is + ordered by type name, and the types that sort first are typically tiny, so its sample + credited every type with a handful of rows (`81` on a 1.68M-row store whose largest type + held 586,986 rows), while the sample of a per-type partial index sat inside a single key + and credited every key with hundreds (`401`, against a true 542). The planner therefore + preferred the general index over the partial one: 82–366 ms per lookup, 310 ms for a + missing key, against 0–1 ms with full statistics or none at all. Results were identical + throughout; only speed changed. Statistics are no longer sampled: `CreateIndex` runs a + full `ANALYZE` (analyzing the new index alone would mix a full row with whatever the other + indexes hold and can mis-rank them the same way), and connect/disconnect run + `PRAGMA optimize(0x10002)`, SQLite's documented form for long-lived connections. It checks + every table and re-analyzes those whose statistics are missing or whose row count moved + by an order of magnitude, without the temporary analysis limit the default form applies + (plain `PRAGMA optimize`, even after `analysis_limit = 0`, capped at 2,000 rows and + mis-ranked the indexes the same way); once statistics are current it is a no-op. A full + `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on an upgraded 2.2 GB store. + ## 5.3.1 — 2026-10-05 ### Fixed diff --git a/README.md b/README.md index 4e3aa37..23c9f86 100644 --- a/README.md +++ b/README.md @@ -496,8 +496,11 @@ This matters for how they behave: no DDL. Declaring the same index name with a *different* property rebuilds it and drops the old one, and indexes created by older versions are migrated away automatically. Declaring your indexes on every app launch is the intended usage. -- **Statistics are refreshed** with a bounded `ANALYZE` after an index is created, so a - new index is usable by the very next query. +- **Statistics are refreshed** with a full `ANALYZE` after an index is created, so a + new index is usable by the very next query, and `PRAGMA optimize(0x10002)` runs on + connect and disconnect to re-analyze tables whose statistics are missing or stale. + Statistics are never sampled: a sample of the type-ordered general index sees only + the smallest types and would make the planner prefer it over a partial index. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs new file mode 100644 index 0000000..b217d97 --- /dev/null +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -0,0 +1,360 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; + +namespace TychoDB.UnitTests; + +/// +/// Proves the planner statistics TychoDB gathers keep a per-type partial index chosen +/// on a store where many small types sort ahead of one large one. +/// +/// Statistics gathered with an analysis_limit read only the first few hundred +/// entries of each index. The general (FullTypeName, Partition) index is ordered +/// by type name, so its sample sees only the small types and reports a handful of rows +/// per type, while the partial index's sample sits inside one key and reports hundreds +/// of rows per key. The planner then prefers the general index and reads and parses +/// every row of the large type on each lookup. Full statistics, or none at all, keep the +/// partial index chosen. +/// +/// +[TestClass] +public class PlannerStatisticsTests +{ +#if ENCRYPTED + private const string DbPassword = "Password"; +#endif + + // Forty tiny types whose names sort before the test namespace, then one type with + // 20,000 rows over 200 keys. The sample of the general index spans every small type; + // the sample of the partial index spans four keys. + private const int SmallTypeCount = 40; + private const int RowsPerSmallType = 10; + private const int GroupCount = 200; + private const int RowsPerGroup = 100; + private const int WideRowCount = GroupCount * RowsPerGroup; + + private const string IndexName = "group_idx"; + private const string LookupGroup = "G0042"; + + private static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); + + public class WideModel + { + public string Key { get; set; } + + public string GroupId { get; set; } + + public int Seq { get; set; } + } + + [TestMethod] + public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexStaysChosen() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(WideRows(), x => x.Key); + } + + SeedSmallTypes(dbFile); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.GroupId, IndexName); + + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexStaysChosen() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + // Launch 1: the app declares its index before any data exists. + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.GroupId, IndexName); + } + + SeedSmallTypes(dbFile); + + // Launch 2: a sync loads the large type, then the app closes. + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(WideRows(), x => x.Key); + } + + // Launch 3: the index is re-declared (a no-op) and queried. + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.GroupId, IndexName); + + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task Connect_AfterRowsArrivedUnanalyzed_GathersFullStatistics() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.GroupId, IndexName); + } + + // Rows that arrived without any connection gathering statistics for them: what + // the empty store left behind is nothing, or zeros, depending on the SQLite build. + SeedSmallTypes(dbFile); + SeedWideRowsDirectly(dbFile); + ReadStatRows(dbFile).ShouldAllBe(row => row.EndsWith(" 0 0 0", StringComparison.Ordinal)); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + AssertPartialIndexChosen(dbFile); + } + + // ---------- assertions ---------- + private static void AssertPartialIndexChosen(string dbFile) + { + var physicalName = ReadPhysicalIndexName(dbFile); + var plan = ExplainGroupLookup(dbFile); + + plan.ShouldContain($"USING INDEX {physicalName}", Case.Sensitive); + plan.ShouldNotContain("idx_jsonvalue_fulltypename_partition", Case.Sensitive); + + // (Partition, JSON_EXTRACT(...)) over every row of the type, with RowsPerGroup + // rows per key: statistics read from the whole index, not a sample of it. + ReadStat(dbFile, physicalName).ShouldBe($"{WideRowCount} {WideRowCount} {RowsPerGroup}"); + } + + private static FilterBuilder GroupFilter() + => FilterBuilder.Create().Filter(FilterType.Equals, x => x.GroupId, LookupGroup); + + private static string ExplainGroupLookup(string dbFile) + { + var sb = new StringBuilder(Queries.SelectDataFromJsonValueWithFullTypeName); + var parameters = new FilterParameters(); + GroupFilter().Build(sb, Serializer, parameters); + + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // SQL is produced by the library's own builders. + command.CommandText = "EXPLAIN QUERY PLAN " + sb; +#pragma warning restore CA2100 + + command.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); + command.Parameters.AddWithValue("$partition", string.Empty); + for (int i = 0; i < parameters.Count; i++) + { + command.Parameters.AddWithValue( + FilterParameters.ParameterPrefix + i.ToString(System.Globalization.CultureInfo.InvariantCulture), + parameters.Values[i] ?? (object)DBNull.Value); + } + + var plan = new StringBuilder(); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + plan.AppendLine(reader.GetString(reader.FieldCount - 1)); + } + + return plan.ToString(); + } + + private static string ReadPhysicalIndexName(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT PhysicalName FROM TychoIndex WHERE IndexName = $indexName"; + command.Parameters.AddWithValue("$indexName", IndexName); + return (string)command.ExecuteScalar(); + } + + private static string ReadStat(string dbFile, string indexName) + { + using var conn = OpenInspection(dbFile); + if (!HasStatTable(conn)) + { + return null; + } + + using var command = conn.CreateCommand(); + command.CommandText = "SELECT stat FROM sqlite_stat1 WHERE idx = $idx"; + command.Parameters.AddWithValue("$idx", indexName); + return command.ExecuteScalar() as string; + } + + private static List ReadStatRows(string dbFile) + { + var rows = new List(); + + using var conn = OpenInspection(dbFile); + if (!HasStatTable(conn)) + { + return rows; + } + + using var command = conn.CreateCommand(); + command.CommandText = "SELECT idx || ' ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue'"; + + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + rows.Add(reader.GetString(0)); + } + + return rows; + } + + private static bool HasStatTable(SqliteConnection conn) + { + using var command = conn.CreateCommand(); + command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; + return command.ExecuteScalar() is not null; + } + + // ---------- seeding ---------- + private static List WideRows() + { + var rows = new List(WideRowCount); + for (int i = 0; i < WideRowCount; i++) + { + rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i }); + } + + return rows; + } + + private static string GroupId(int i) + => "G" + (i % GroupCount).ToString("D4", System.Globalization.CultureInfo.InvariantCulture); + + private static void SeedSmallTypes(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var transaction = conn.BeginTransaction(); + using var insert = conn.CreateCommand(); + insert.Transaction = transaction; + insert.CommandText = + "INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) " + + "VALUES ($key, $fullTypeName, '', json_object('Id', $key))"; + + var key = insert.Parameters.Add("$key", SqliteType.Text); + var fullTypeName = insert.Parameters.Add("$fullTypeName", SqliteType.Text); + + for (int t = 0; t < SmallTypeCount; t++) + { + fullTypeName.Value = "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); + for (int i = 0; i < RowsPerSmallType; i++) + { + key.Value = "small-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + insert.ExecuteNonQuery(); + } + } + + transaction.Commit(); + } + + private static void SeedWideRowsDirectly(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var transaction = conn.BeginTransaction(); + using var insert = conn.CreateCommand(); + insert.Transaction = transaction; + insert.CommandText = + "INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) " + + "VALUES ($key, $fullTypeName, '', json_object('Key', $key, 'GroupId', $groupId, 'Seq', $seq))"; + + var key = insert.Parameters.Add("$key", SqliteType.Text); + var fullTypeName = insert.Parameters.Add("$fullTypeName", SqliteType.Text); + var groupId = insert.Parameters.Add("$groupId", SqliteType.Text); + var seq = insert.Parameters.Add("$seq", SqliteType.Integer); + + fullTypeName.Value = typeof(WideModel).FullName; + + foreach (var row in WideRows()) + { + key.Value = row.Key; + groupId.Value = row.GroupId; + seq.Value = row.Seq; + insert.ExecuteNonQuery(); + } + + transaction.Commit(); + } + + // ---------- plumbing ---------- + private static (string Path, string DbName) NewDbPath() + { + var dir = Path.Combine(Path.GetTempPath(), "tycho_planner_statistics_tests"); + Directory.CreateDirectory(dir); + return (dir, $"{Guid.NewGuid()}.db"); + } + + private static Tycho BuildDb(string path, string dbName) + { +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: true, requireTypeRegistration: false); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: true, requireTypeRegistration: false); +#endif + } + + /// Reopens an existing database without rebuilding it. + private static Tycho BuildDb2(string path, string dbName) + { + SqliteConnection.ClearAllPools(); +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false); +#endif + } + + /// + /// Opens an inspection connection carrying the same key the database was created with. + /// Tycho holds locking_mode = EXCLUSIVE and pooling keeps a disposed connection's lock + /// alive, so the pool must be cleared after the Tycho instance is disposed and before + /// the file is reopened. + /// + private static SqliteConnection OpenInspection(string dbFile) + { + SqliteConnection.ClearAllPools(); + + var connectionStringBuilder = + new SqliteConnectionStringBuilder + { + ConnectionString = $"Filename={dbFile}", + Cache = SqliteCacheMode.Private, + Mode = SqliteOpenMode.ReadWriteCreate, + }; + +#if ENCRYPTED + connectionStringBuilder.Password = DbPassword; +#endif + + var conn = new SqliteConnection(connectionStringBuilder.ToString()); + conn.Open(); + return conn; + } +} diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 3ac92fe..09f8527 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -561,9 +561,18 @@ public static string EscapeSqlLiteral(string value) public static string DropIndex(string fullIndexName) => string.Concat(DropIndexPrefix, fullIndexName, ";"); - // Bounded ANALYZE: refreshes sqlite_stat1 so a newly created index is usable by - // the very next query. analysis_limit caps the work so this stays cheap on mobile. - public const string AnalyzeBounded = "PRAGMA analysis_limit = 400; ANALYZE;"; + // Full ANALYZE: refreshes sqlite_stat1 so a newly created index is usable by the + // very next query. Every index is read in full: a sample (analysis_limit) of the + // type-ordered general index sees only the smallest types and makes the planner + // prefer it over the per-type partial index (see Tycho.RunOptimize). ANALYZE of + // the new index alone would mix a full row with whatever the others hold and can + // produce the same mis-ranking. + public const string Analyze = "PRAGMA analysis_limit = 0; ANALYZE;"; + + // SQLite's recommended form for a long-lived connection: check every table and + // re-analyze those that need it, without the temporary analysis_limit the default + // mask (0xfffe, bit 0x10) applies. A no-op when statistics are current. + public const string PragmaOptimize = "PRAGMA optimize(0x10002);"; public const string SelectIndexMetadata = """ diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 82fcfa7..6fad89b 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -298,14 +298,23 @@ public async ValueTask DisconnectAsync() } /// - /// Runs SQLite's recommended PRAGMA optimize (bounded by - /// analysis_limit), refreshing query-planner statistics so indexes — - /// including expression indexes over JSON_EXTRACT — keep being chosen. + /// Runs PRAGMA optimize(0x10002), the form SQLite recommends for a + /// long-lived connection at open: it checks every table, not just those already + /// queried, and re-analyzes any whose indexes lack statistics or whose row count + /// moved by an order of magnitude, so expression indexes over JSON_EXTRACT keep + /// being chosen. Otherwise a no-op. /// - /// Called both when opening and when closing a connection. The open-time call is - /// what SQLite recommends for long-lived processes: a mobile app that connects - /// once and never cleanly disconnects would otherwise run its entire lifetime on - /// default planner heuristics. + /// The mask leaves out the temporary analysis_limit the default form + /// applies. Statistics must be read from the whole of each index: the general + /// (FullTypeName, Partition) index is ordered by type name, so a sample of + /// its first few hundred entries sees only the smallest types and credits every + /// type with a handful of rows, while a sample of a per-type partial index sits + /// inside one key and credits every key with hundreds. The planner then prefers + /// the general index and reads every row of the type on each lookup. + /// + /// + /// Called both when opening and when closing a connection. The open-time call + /// covers a mobile app that connects once and never cleanly disconnects. /// /// Best-effort: failures never block connect or teardown. /// @@ -314,7 +323,7 @@ private static void RunOptimize(SqliteConnection connection) try { using var command = connection.CreateCommand(); - command.CommandText = "PRAGMA analysis_limit = 400; PRAGMA optimize;"; + command.CommandText = Queries.PragmaOptimize; command.ExecuteNonQuery(); } catch @@ -2287,7 +2296,7 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de // Disconnect. Advisory: a failure here must not fail index creation. try { - ExecuteNonQuery(conn, Queries.AnalyzeBounded); + ExecuteNonQuery(conn, Queries.Analyze); } catch { From f3023f5b23d6e20f268fc49f97c5f09c03124efa Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 9 Oct 2026 18:39:00 -0500 Subject: [PATCH 02/25] fix: repair sampled statistics left by earlier releases on first connect PRAGMA optimize(0x10002) only re-analyzes a table whose indexes lack statistics or whose row count moved tenfold, so the sampled rows 5.3.1 wrote survive it and the slow plan persists. A store without the user_version stamp now gets one full ANALYZE at connect and is stamped; a stamped store gets PRAGMA optimize(0x10002). The stamp is written only when the stored value is lower, so a higher version is never lowered. --- CHANGELOG.md | 5 ++ README.md | 6 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 76 +++++++++++++++++++++ TychoDB/Queries.cs | 11 +++ TychoDB/Tycho.cs | 57 ++++++++++++---- 5 files changed, 141 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cb4122..2ced6d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,11 @@ (plain `PRAGMA optimize`, even after `analysis_limit = 0`, capped at 2,000 rows and mis-ranked the indexes the same way); once statistics are current it is a no-op. A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on an upgraded 2.2 GB store. + A store written by an earlier 5.x release already holds sampled rows, which + `PRAGMA optimize` never revisits (nothing is missing and nothing has grown), so the first + connect of such a store runs one full `ANALYZE` and stamps it with `PRAGMA user_version = 1` + (a higher value is never lowered). If an earlier release writes to the store after that, + its sampled rows return and are not detected. ## 5.3.1 — 2026-10-05 diff --git a/README.md b/README.md index 23c9f86..b073c75 100644 --- a/README.md +++ b/README.md @@ -499,8 +499,10 @@ This matters for how they behave: - **Statistics are refreshed** with a full `ANALYZE` after an index is created, so a new index is usable by the very next query, and `PRAGMA optimize(0x10002)` runs on connect and disconnect to re-analyze tables whose statistics are missing or stale. - Statistics are never sampled: a sample of the type-ordered general index sees only - the smallest types and would make the planner prefer it over a partial index. + A store written by 5.3.1 or earlier gets one full `ANALYZE` on its first connect, to + replace the sampled statistics those versions wrote. Statistics are never sampled: a + sample of the type-ordered general index sees only the smallest types and would make + the planner prefer it over a partial index. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index b217d97..dbba02f 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -133,6 +133,42 @@ public async Task Connect_AfterRowsArrivedUnanalyzed_GathersFullStatistics() AssertPartialIndexChosen(dbFile); } + [TestMethod] + public async Task Connect_RepairsSampledStatisticsLeftByAnEarlierRelease() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + LeaveSampledStatistics(dbFile); + ExplainGroupLookup(dbFile).ShouldContain("idx_jsonvalue_fulltypename_partition", Case.Sensitive); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + ReadUserVersion(dbFile).ShouldBe((long)Queries.FullStatisticsUserVersion); + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task Connect_DoesNotLowerAHigherUserVersion() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + SetUserVersion(dbFile, 7); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, "seq_idx"); + } + + ReadUserVersion(dbFile).ShouldBe(7L); + } + // ---------- assertions ---------- private static void AssertPartialIndexChosen(string dbFile) { @@ -234,7 +270,47 @@ private static bool HasStatTable(SqliteConnection conn) return command.ExecuteScalar() is not null; } + private static long ReadUserVersion(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "PRAGMA user_version"; + return (long)command.ExecuteScalar(); + } + + private static void SetUserVersion(string dbFile, int value) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // A test-chosen integer literal. + command.CommandText = "PRAGMA user_version = " + value.ToString(System.Globalization.CultureInfo.InvariantCulture); +#pragma warning restore CA2100 + + command.ExecuteNonQuery(); + } + // ---------- seeding ---------- + private static async Task SeedIndexedStore(string path, string dbName) + { + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(WideRows(), x => x.Key); + await db.CreateIndexAsync(x => x.GroupId, IndexName); + } + + SeedSmallTypes(Path.Combine(path, dbName)); + } + + /// Leaves what 5.3.1 left: statistics sampled at 400 rows, and no version stamp. + private static void LeaveSampledStatistics(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE; PRAGMA user_version = 0;"; + command.ExecuteNonQuery(); + } + private static List WideRows() { var rows = new List(WideRowCount); diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 09f8527..44f5217 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -569,6 +569,17 @@ public static string DropIndex(string fullIndexName) // produce the same mis-ranking. public const string Analyze = "PRAGMA analysis_limit = 0; ANALYZE;"; + // PRAGMA user_version of a store whose statistics were gathered in full at least + // once. A store written by an earlier 5.x release reads 0 and may hold sampled + // rows, which PRAGMA optimize never revisits (nothing is missing and nothing has + // grown), so the first connect runs Analyze instead of PragmaOptimize. Written + // only when the stored value is lower, so a higher version is never lowered. + public const int FullStatisticsUserVersion = 1; + + public const string UserVersion = "PRAGMA user_version;"; + + public const string StampFullStatistics = "PRAGMA user_version = 1;"; + // SQLite's recommended form for a long-lived connection: check every table and // re-analyze those that need it, without the temporary analysis_limit the default // mask (0xfffe, bit 0x10) applies. A no-op when statistics are current. diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 6fad89b..a9dfc6d 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -298,11 +298,11 @@ public async ValueTask DisconnectAsync() } /// - /// Runs PRAGMA optimize(0x10002), the form SQLite recommends for a - /// long-lived connection at open: it checks every table, not just those already - /// queried, and re-analyzes any whose indexes lack statistics or whose row count - /// moved by an order of magnitude, so expression indexes over JSON_EXTRACT keep - /// being chosen. Otherwise a no-op. + /// Runs PRAGMA optimize(0x10002) when a connection closes: it checks every + /// table, not just those already queried, and re-analyzes any whose indexes lack + /// statistics or whose row count moved by an order of magnitude, so expression + /// indexes over JSON_EXTRACT keep being chosen. Otherwise a no-op. The open-time + /// counterpart is . /// /// The mask leaves out the temporary analysis_limit the default form /// applies. Statistics must be read from the whole of each index: the general @@ -312,11 +312,7 @@ public async ValueTask DisconnectAsync() /// inside one key and credits every key with hundreds. The planner then prefers /// the general index and reads every row of the type on each lookup. /// - /// - /// Called both when opening and when closing a connection. The open-time call - /// covers a mobile app that connects once and never cleanly disconnects. - /// - /// Best-effort: failures never block connect or teardown. + /// Best-effort: failures never block teardown. /// private static void RunOptimize(SqliteConnection connection) { @@ -332,6 +328,43 @@ private static void RunOptimize(SqliteConnection connection) } } + /// + /// Gathers planner statistics for a freshly opened connection, which covers a + /// mobile app that connects once and never cleanly disconnects. A store stamped + /// with gets the same + /// PRAGMA optimize(0x10002) as ; a store written by + /// an earlier release gets one full ANALYZE, because the sampled rows those + /// releases wrote are neither missing nor stale by SQLite's rules and would + /// otherwise persist. Best-effort: failures never block connect. + /// + private static void RefreshStatistics(SqliteConnection connection) + { + try + { + using var command = connection.CreateCommand(); + command.CommandText = Queries.UserVersion; + long userVersion = command.ExecuteScalar() is long version ? version : 0L; + + if (userVersion < Queries.FullStatisticsUserVersion) + { + command.CommandText = Queries.Analyze; + command.ExecuteNonQuery(); + + command.CommandText = Queries.StampFullStatistics; + command.ExecuteNonQuery(); + } + else + { + command.CommandText = Queries.PragmaOptimize; + command.ExecuteNonQuery(); + } + } + catch + { + // Statistics are an optimization, not a correctness requirement. + } + } + public void Backup(SqliteConnection backupDatabaseConnection) { _connection?.BackupDatabase(backupDatabaseConnection); @@ -2993,7 +3026,7 @@ private SqliteConnection BuildConnection() command.ExecuteNonQuery(); - RunOptimize(conn); + RefreshStatistics(conn); }, _persistConnection); @@ -3024,7 +3057,7 @@ private async ValueTask BuildConnectionAsync(CancellationToken command.ExecuteNonQuery(); - RunOptimize(connection); + RefreshStatistics(connection); return connection; } From f7ee589518bda9004e7f8173275cd3a59b35f794 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 9 Oct 2026 18:44:27 -0500 Subject: [PATCH 03/25] feat: add autoOptimize opt-out and Optimize()/OptimizeAsync() Connecting a store written by an earlier version drops the four redundant indexes 4.x created and gathers planner statistics, which can stall the first launch of a large upgraded store for 10-30 s on the connecting thread. autoOptimize (default true) keeps that behavior; false connects without the drops, the statistics step and the ANALYZE after CreateIndex, leaving them to Optimize()/OptimizeAsync(), which do exactly the work connect skipped: the drops, then a full ANALYZE on a store written by an earlier release or PRAGMA optimize(0x10002) otherwise, so a call with nothing to do costs ~0 ms. Disconnect is unaffected. --- CHANGELOG.md | 19 +++ README.md | 19 ++- TychoDB.UnitTests/IndexDdlTests.cs | 50 +++++- TychoDB.UnitTests/PlannerStatisticsTests.cs | 114 +++++++++++++- TychoDB/Queries.cs | 37 +++-- TychoDB/Tycho.cs | 160 +++++++++++++++----- 6 files changed, 344 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ced6d4..91ff961 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,25 @@ (a higher value is never lowered). If an earlier release writes to the store after that, its sampled rows return and are not detected. +### Added + +- **`autoOptimize` constructor parameter (default `true`), `Optimize()` and + `OptimizeAsync()`.** Connecting a store written by an earlier version does one-time work + on the connecting thread: it drops the four redundant indexes 4.x created — most of a + 10–30 s first launch measured on a large upgraded store, since freeing an index's pages + takes time proportional to its size and SQLCipher's default `secure_delete` writes every + freed page back — and gathers planner statistics (3.2 s / 17.5 s above when they are + missing, sampled or stale). Pass `autoOptimize: false` to connect without either, and + without the `ANALYZE` after `CreateIndex` (a new index is chosen by default heuristics + until its statistics arrive); then call `Optimize()` or `OptimizeAsync()` when convenient + — on a loading page, for example. They do exactly the work connect skipped: the drops, + then a full `ANALYZE` on a store written by an earlier release or `PRAGMA optimize(0x10002)` + otherwise, so a call with nothing to do costs ~0 ms. They hold the single connection for the + duration, so every other operation on the instance waits (17–24 s on the 2.2 GB store), and + run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` + alone does not move the work off the caller — so call them from a background thread. The + disconnect-time `PRAGMA optimize` is unaffected by the opt-out. + ## 5.3.1 — 2026-10-05 ### Fixed diff --git a/README.md b/README.md index b073c75..fe5b7d1 100644 --- a/README.md +++ b/README.md @@ -502,7 +502,11 @@ This matters for how they behave: A store written by 5.3.1 or earlier gets one full `ANALYZE` on its first connect, to replace the sampled statistics those versions wrote. Statistics are never sampled: a sample of the type-ordered general index sees only the smallest types and would make - the planner prefer it over a partial index. + the planner prefer it over a partial index. Together with dropping the redundant + indexes 4.x created, that connect-time work can stall the first launch of a large + upgraded store for 10–30 s; pass `autoOptimize: false` to skip it (and the `ANALYZE` + after `CreateIndex`) and call `Optimize()` / `OptimizeAsync()` from a background thread + instead — the same work, ~0 ms when nothing changed. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). @@ -546,6 +550,13 @@ db.Disconnect(); // Or disconnect asynchronously await db.DisconnectAsync(); + +// Open without the one-time upgrade work (dropping indexes left by earlier versions and +// gathering statistics can stall the first launch of a large store for 10–30 s) and run +// the same work later, from a background thread — on a loading page, for example +var deferredDb = new Tycho(dbPath: "./data", jsonSerializer: serializer, autoOptimize: false); +await deferredDb.ConnectAsync(); +await Task.Run(() => deferredDb.Optimize()); ``` ### Device Performance Profiles @@ -598,6 +609,12 @@ await db.DeleteObjectsAsync(); ```csharp // Optimize database performance and reduce size db.Cleanup(shrinkMemory: true, vacuum: true); + +// Drop indexes left by earlier versions and bring planner statistics up to date; ~0 ms +// when nothing changed. Holds the connection for the duration — every other operation on +// this instance waits; 17–24 s on a 2.2 GB store upgraded from 4.x — and runs on the +// calling thread, so call it from a background thread, never the UI thread. +await Task.Run(() => db.Optimize()); ``` ## LINQ Support diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 4576e26..c32ba23 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -510,6 +510,50 @@ public async Task LegacyDatabase_ShedsRedundantIndexesOnConnect() after.ShouldNotContainKey("idx_streamvalue_key_partition"); } + [TestMethod] + public async Task LegacyDatabase_WithAutoOptimizeOff_KeepsRedundantIndexesUntilOptimize() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(SeedData(), x => x.StringProperty); + } + + using (var conn = OpenInspection(dbFile)) + { + using var command = conn.CreateCommand(); + command.CommandText = + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_fulltypename ON JsonValue (FullTypeName);" + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_key_fulltypename ON JsonValue (Key, FullTypeName);" + + "CREATE INDEX IF NOT EXISTS idx_streamvalue_key_partition ON StreamValue (Key, Partition);"; + command.ExecuteNonQuery(); + } + + // With autoOptimize off, connect leaves the legacy indexes in place; freeing + // their pages is Optimize's job. + using (await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + } + + var kept = ReadIndexDdl(dbFile); + kept.ShouldContainKey("idx_jsonvalue_fulltypename"); + kept.ShouldContainKey("idx_jsonvalue_key_fulltypename"); + kept.ShouldContainKey("idx_streamvalue_key_partition"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + } + + var after = ReadIndexDdl(dbFile); + after.ShouldNotContainKey("idx_jsonvalue_fulltypename"); + after.ShouldNotContainKey("idx_jsonvalue_key_fulltypename"); + after.ShouldNotContainKey("idx_streamvalue_key_partition"); + after.ShouldContainKey("idx_jsonvalue_fulltypename_partition"); + } + [TestMethod] public async Task StringPathSort_CanRequestNumericForm_AndUsesTheNumericIndex() { @@ -714,13 +758,13 @@ private static Tycho BuildDb(string path, string dbName) } /// Reopens an existing database without rebuilding it. - private static Tycho BuildDb2(string path, string dbName) + private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = true) { SqliteConnection.ClearAllPools(); #if ENCRYPTED - return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false); + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); #else - return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false); + return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); #endif } diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index dbba02f..1370165 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -169,6 +169,99 @@ public async Task Connect_DoesNotLowerAHigherUserVersion() ReadUserVersion(dbFile).ShouldBe(7L); } + [TestMethod] + public async Task Connect_WithAutoOptimizeOff_LeavesStatisticsUntilOptimizeIsCalled() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + LeaveSampledStatistics(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + // Neither connecting nor disposing touched the sampled rows. + ReadUserVersion(dbFile).ShouldBe(0L); + ExplainGroupLookup(dbFile).ShouldContain("idx_jsonvalue_fulltypename_partition", Case.Sensitive); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + (await db.OptimizeAsync()).ShouldBeTrue(); + } + + ReadUserVersion(dbFile).ShouldBe((long)Queries.FullStatisticsUserVersion); + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task Optimize_OnStoreFromAnEarlierRelease_GathersFullStatistics() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + LeaveSampledStatistics(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + } + + ReadUserVersion(dbFile).ShouldBe((long)Queries.FullStatisticsUserVersion); + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task Optimize_WithCurrentStatistics_LeavesThemAlone() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + var before = ReadStatRows(dbFile); + before.ShouldNotBeEmpty(); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + } + + ReadStatRows(dbFile).ShouldBe(before, ignoreOrder: true); + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task CreateIndex_WithAutoOptimizeOff_LeavesStatisticsToOptimize() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(WideRows(), x => x.Key); + } + + SeedSmallTypes(dbFile); + + // The connection closes between operations, so the file can be inspected while + // the instance is alive. + using var detached = BuildDetachedDb(path, dbName).Connect(); + + await detached.CreateIndexAsync(x => x.GroupId, IndexName); + + var physicalName = ReadPhysicalIndexName(dbFile); + ReadStat(dbFile, physicalName).ShouldBeNull(); + ExplainGroupLookup(dbFile).ShouldContain($"USING INDEX {physicalName}", Case.Sensitive); + (await detached.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + + detached.Optimize(); + + AssertPartialIndexChosen(dbFile); + } + // ---------- assertions ---------- private static void AssertPartialIndexChosen(string dbFile) { @@ -397,13 +490,28 @@ private static Tycho BuildDb(string path, string dbName) } /// Reopens an existing database without rebuilding it. - private static Tycho BuildDb2(string path, string dbName) + private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = true) + { + SqliteConnection.ClearAllPools(); +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#endif + } + + /// + /// Reopens an existing database, opted out of automatic maintenance, with a + /// connection that closes between operations and no pooling, so an inspection + /// connection can read the file while the instance is alive. + /// + private static Tycho BuildDetachedDb(string path, string dbName) { SqliteConnection.ClearAllPools(); #if ENCRYPTED - return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false); + return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: false, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: false, autoOptimize: false); #else - return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false); + return new Tycho(path, Serializer, dbName, persistConnection: false, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: false, autoOptimize: false); #endif } diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 44f5217..a871810 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -46,15 +46,6 @@ PRIMARY KEY (Key, FullTypeName, Partition) CREATE INDEX IF NOT EXISTS idx_jsonvalue_fulltypename_partition ON JsonValue (FullTypeName, Partition); - -- Shed indexes that earlier versions created and that duplicate either the - -- primary-key autoindex or a prefix of the index above. Each one cost a - -- full b-tree of write maintenance on every insert, update and delete while - -- serving no query the remaining indexes cannot. Idempotent and cheap. - DROP INDEX IF EXISTS idx_jsonvalue_fulltypename; - DROP INDEX IF EXISTS idx_jsonvalue_key_fulltypename; - DROP INDEX IF EXISTS idx_jsonvalue_key_fulltypename_partition; - DROP INDEX IF EXISTS idx_streamvalue_key_partition; - CREATE TABLE IF NOT EXISTS StreamValue ( Key TEXT NOT NULL, @@ -74,6 +65,21 @@ PRIMARY KEY (IndexName, FullTypeName) ); """; + // Indexes earlier versions created that duplicate either the primary-key autoindex + // or a prefix of idx_jsonvalue_fulltypename_partition. Each one costs a full b-tree + // of write maintenance on every insert, update and delete while serving no query + // the remaining indexes cannot. Idempotent, and a no-op once they are gone; but + // freeing their pages on an upgraded store takes time proportional to their size, + // so the connect script includes this only when autoOptimize is on (see + // Tycho.Optimize). + public const string DropLegacyIndexes = + """ + DROP INDEX IF EXISTS idx_jsonvalue_fulltypename; + DROP INDEX IF EXISTS idx_jsonvalue_key_fulltypename; + DROP INDEX IF EXISTS idx_jsonvalue_key_fulltypename_partition; + DROP INDEX IF EXISTS idx_streamvalue_key_partition; + """; + // Profile defaults. cache_size is in KiB (negative = KiB, not pages); // mmap_size is in bytes; wal_autocheckpoint is in pages. private const int MobileCacheSizeKb = 8_000; // ~8 MB page cache @@ -91,12 +97,14 @@ PRIMARY KEY (IndexName, FullTypeName) /// /// Builds the full per-connection setup script (PRAGMAs + schema DDL) for the - /// given performance profile, honoring optional cache-size / mmap overrides. + /// given performance profile, honoring optional cache-size / mmap overrides, and + /// shedding the indexes earlier versions created unless told not to. /// public static string BuildConnectionScript( TychoPerformanceProfile profile, int? cacheSizeKbOverride = null, - long? mmapSizeBytesOverride = null) + long? mmapSizeBytesOverride = null, + bool dropLegacyIndexes = true) { bool desktop = profile == TychoPerformanceProfile.Desktop; @@ -105,7 +113,7 @@ public static string BuildConnectionScript( int walAutocheckpoint = desktop ? DesktopWalAutocheckpoint : MobileWalAutocheckpoint; long journalSizeLimit = desktop ? DesktopJournalSizeLimitBytes : MobileJournalSizeLimitBytes; - var sb = new System.Text.StringBuilder(SharedPragmas.Length + SchemaDdl.Length + 160); + var sb = new System.Text.StringBuilder(SharedPragmas.Length + SchemaDdl.Length + DropLegacyIndexes.Length + 160); var ic = System.Globalization.CultureInfo.InvariantCulture; sb.Append(SharedPragmas).Append('\n') @@ -115,6 +123,11 @@ public static string BuildConnectionScript( .Append("PRAGMA journal_size_limit = ").Append(journalSizeLimit.ToString(ic)).Append(";\n\n") .Append(SchemaDdl); + if (dropLegacyIndexes) + { + sb.Append('\n').Append(DropLegacyIndexes); + } + return sb.ToString(); } diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index a9dfc6d..4547226 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -47,6 +47,7 @@ private const string private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; + private readonly bool _autoOptimize; // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -104,6 +105,16 @@ private const string /// Selects device-appropriate SQLite PRAGMA tuning. Default is . /// Optional override for the SQLite page cache size, in KiB. Overrides the profile default. /// Optional override for the SQLite memory-map size, in bytes (0 disables mmap). Overrides the profile default. + /// + /// Whether this instance maintains the store on its own: at connect it drops the + /// redundant indexes 4.x created and gathers planner statistics when the store has + /// none, they were sampled by an earlier release, or a table has grown tenfold, and + /// it refreshes statistics after CreateIndex. That work runs on the connecting + /// thread and can take 10–30 s on a large store upgraded from 4.x; pass false to + /// connect without it and call or + /// from a background thread at a convenient time, which does the same work. + /// Statistics are still refreshed when the connection closes. Default is true. + /// public Tycho( string dbPath, IJsonSerializer jsonSerializer, @@ -116,7 +127,8 @@ public Tycho( int commandTimeout = 30, TychoPerformanceProfile performanceProfile = TychoPerformanceProfile.Mobile, int? cacheSizeKb = null, - long? mmapSizeBytes = null) + long? mmapSizeBytes = null, + bool autoOptimize = true) { SQLitePCL.Batteries_V2.Init(); @@ -153,7 +165,8 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; - _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes); + _autoOptimize = autoOptimize; + _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize); } /// @@ -341,23 +354,7 @@ private static void RefreshStatistics(SqliteConnection connection) { try { - using var command = connection.CreateCommand(); - command.CommandText = Queries.UserVersion; - long userVersion = command.ExecuteScalar() is long version ? version : 0L; - - if (userVersion < Queries.FullStatisticsUserVersion) - { - command.CommandText = Queries.Analyze; - command.ExecuteNonQuery(); - - command.CommandText = Queries.StampFullStatistics; - command.ExecuteNonQuery(); - } - else - { - command.CommandText = Queries.PragmaOptimize; - command.ExecuteNonQuery(); - } + GatherStatistics(connection); } catch { @@ -365,6 +362,31 @@ private static void RefreshStatistics(SqliteConnection connection) } } + /// + /// The work of , letting failures propagate so that + /// reports them. + /// + private static void GatherStatistics(SqliteConnection connection) + { + using var command = connection.CreateCommand(); + command.CommandText = Queries.UserVersion; + long userVersion = command.ExecuteScalar() is long version ? version : 0L; + + if (userVersion < Queries.FullStatisticsUserVersion) + { + command.CommandText = Queries.Analyze; + command.ExecuteNonQuery(); + + command.CommandText = Queries.StampFullStatistics; + command.ExecuteNonQuery(); + } + else + { + command.CommandText = Queries.PragmaOptimize; + command.ExecuteNonQuery(); + } + } + public void Backup(SqliteConnection backupDatabaseConnection) { _connection?.BackupDatabase(backupDatabaseConnection); @@ -2278,7 +2300,7 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) /// with no DDL and no ANALYZE. /// /// - private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) + private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition, bool analyze) { using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); @@ -2326,14 +2348,20 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de // Refresh planner statistics outside the transaction so the index just // created is usable by the very next query rather than only after a - // Disconnect. Advisory: a failure here must not fail index creation. - try + // Disconnect. Advisory: a failure here must not fail index creation. An + // instance that opted out of automatic maintenance leaves this to Optimize; + // until then the planner estimates the new index by default heuristics, + // which still favor it. + if (analyze) { - ExecuteNonQuery(conn, Queries.Analyze); - } - catch - { - // Statistics are an optimization, not a correctness requirement. + try + { + ExecuteNonQuery(conn, Queries.Analyze); + } + catch + { + // Statistics are an optimization, not a correctness requirement. + } } return true; @@ -2410,8 +2438,8 @@ private Tycho CreateIndexCore( _connection .WithConnectionBlock( _connectionGate, - definition, - static (conn, state) => ExecuteCreateIndex(conn, state), + (definition, analyze: _autoOptimize), + static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.analyze), _persistConnection); return this; @@ -2436,8 +2464,8 @@ private ValueTask CreateIndexCoreAsync( return _connection .WithConnectionBlockAsync( _connectionGate, - definition, - static (conn, state) => ExecuteCreateIndex(conn, state), + (definition, analyze: _autoOptimize), + static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.analyze), _persistConnection, cancellationToken); } @@ -2680,6 +2708,60 @@ public IReadOnlyList ListIndexes() _persistConnection); } + /// + /// Does the maintenance connecting does on its own when autoOptimize is on: + /// drops the redundant indexes earlier versions created, then gathers planner + /// statistics — a full ANALYZE on a store written by an earlier release, + /// otherwise PRAGMA optimize(0x10002), which re-analyzes only tables whose + /// indexes lack statistics or whose row count moved tenfold. With nothing to do it + /// costs ~0 ms, so calling it on every launch is fine. + /// + /// Holds the database's single connection for the duration, so every other + /// operation on this instance waits: the first run on a 2.2 GB store upgraded from + /// 4.x took 17–24 s, and a re-analysis 3.2 s on a 1.68M-row store. The work runs on + /// the calling thread — Microsoft.Data.Sqlite executes synchronously, so + /// does not move it off the caller by itself — and must + /// not be called from a UI thread. + /// + /// + public void Optimize() + { + ArgumentNullException.ThrowIfNull(_connection); + + _connection + .WithConnectionBlock( + _connectionGate, + static conn => OptimizeStore(conn), + _persistConnection); + } + + /// + /// Asynchronously does what does, with the same cost. It + /// holds the database's single connection for the duration and runs on the calling + /// thread — Microsoft.Data.Sqlite executes synchronously, so this method does not + /// move the work off the caller by itself — and must not be called from a UI thread. + /// + /// A token to cancel the asynchronous operation. + /// A ValueTask containing true when the store was optimized. + public ValueTask OptimizeAsync(CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(_connection); + + return _connection + .WithConnectionBlockAsync( + _connectionGate, + static conn => OptimizeStore(conn), + _persistConnection, + cancellationToken); + } + + private static bool OptimizeStore(SqliteConnection conn) + { + ExecuteNonQuery(conn, Queries.DropLegacyIndexes); + GatherStatistics(conn); + return true; + } + /// /// Performs database cleanup operations to optimize performance and reduce size. /// @@ -3008,8 +3090,8 @@ private SqliteConnection BuildConnection() connection .WithConnectionBlock( _connectionGate, - _connectionScript, - static (conn, script) => + (script: _connectionScript, autoOptimize: _autoOptimize), + static (conn, state) => { conn.Open(); @@ -3021,12 +3103,15 @@ private SqliteConnection BuildConnection() // Profile PRAGMAs + idempotent schema/index creation. Composed from // library constants and numeric profile values only (no user input). #pragma warning disable CA2100 - command.CommandText = script; + command.CommandText = state.script; #pragma warning restore CA2100 command.ExecuteNonQuery(); - RefreshStatistics(conn); + if (state.autoOptimize) + { + RefreshStatistics(conn); + } }, _persistConnection); @@ -3057,7 +3142,10 @@ private async ValueTask BuildConnectionAsync(CancellationToken command.ExecuteNonQuery(); - RefreshStatistics(connection); + if (_autoOptimize) + { + RefreshStatistics(connection); + } return connection; } From ae6a6af3bdcac9529c61a290f1abed50eb3e4522 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 9 Oct 2026 18:51:06 -0500 Subject: [PATCH 04/25] fix: make PRAGMA optimize consider JsonValue on SQLite before 3.46 SQLite before 3.46 (the SQLCipher build is 3.39.2) ignores the 0x10000 bit and lets PRAGMA optimize consider only tables the connection's planner has used, so a connection that had run no query yet analyzed nothing at connect, at disconnect and in Optimize(). A probe read of JsonValue now precedes the pragma so every build behaves the same. --- CHANGELOG.md | 5 ++++- TychoDB/Queries.cs | 7 +++++++ TychoDB/Tycho.cs | 15 +++++++++++---- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91ff961..69bd675 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,10 @@ `PRAGMA optimize` never revisits (nothing is missing and nothing has grown), so the first connect of such a store runs one full `ANALYZE` and stamps it with `PRAGMA user_version = 1` (a higher value is never lowered). If an earlier release writes to the store after that, - its sampled rows return and are not detected. + its sampled rows return and are not detected. On the Encrypted package (SQLite 3.39.2, + which lets `PRAGMA optimize` consider only tables the connection has already queried), a + probe read precedes the pragma so that connect, disconnect and `Optimize` behave the same + as on the plain build. ### Added diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index a871810..5b5a206 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -598,6 +598,13 @@ public static string DropIndex(string fullIndexName) // mask (0xfffe, bit 0x10) applies. A no-op when statistics are current. public const string PragmaOptimize = "PRAGMA optimize(0x10002);"; + // A planned read of JsonValue, run before PragmaOptimize. SQLite before 3.46 (the + // SQLCipher build is 3.39.2) ignores the 0x10000 bit and lets PRAGMA optimize + // consider only tables the connection's planner has used, so a connection that + // has run no query yet would analyze nothing. One index probe makes every build + // behave the same. + public const string TouchJsonValue = "SELECT 1 FROM JsonValue WHERE FullTypeName = '' AND Partition = '' LIMIT 1;"; + public const string SelectIndexMetadata = """ SELECT PhysicalName, Definition, ShapeVersion diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 4547226..30da506 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -332,8 +332,7 @@ private static void RunOptimize(SqliteConnection connection) try { using var command = connection.CreateCommand(); - command.CommandText = Queries.PragmaOptimize; - command.ExecuteNonQuery(); + OptimizeIfNeeded(command); } catch { @@ -341,6 +340,15 @@ private static void RunOptimize(SqliteConnection connection) } } + private static void OptimizeIfNeeded(SqliteCommand command) + { + command.CommandText = Queries.TouchJsonValue; + command.ExecuteScalar(); + + command.CommandText = Queries.PragmaOptimize; + command.ExecuteNonQuery(); + } + /// /// Gathers planner statistics for a freshly opened connection, which covers a /// mobile app that connects once and never cleanly disconnects. A store stamped @@ -382,8 +390,7 @@ private static void GatherStatistics(SqliteConnection connection) } else { - command.CommandText = Queries.PragmaOptimize; - command.ExecuteNonQuery(); + OptimizeIfNeeded(command); } } From fa8f79f1c640ecb56cc679ec7c4ab502c61f8e39 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 9 Oct 2026 18:52:22 -0500 Subject: [PATCH 05/25] docs: describe the sampled-statistics regression, its repro and the fix A write-up for the team (symptom, mechanism, measurements, decisions, limitations) and a self-contained sqlite3 CLI script that reproduces the plan flip on synthetic data in about three seconds. --- docs/planner-statistics-sampling.md | 194 +++++++++++++++++++++++++++ docs/planner-statistics-sampling.sql | 172 ++++++++++++++++++++++++ 2 files changed, 366 insertions(+) create mode 100644 docs/planner-statistics-sampling.md create mode 100644 docs/planner-statistics-sampling.sql diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md new file mode 100644 index 0000000..bde1f17 --- /dev/null +++ b/docs/planner-statistics-sampling.md @@ -0,0 +1,194 @@ +# Sampled planner statistics made SQLite skip the partial indexes (5.3.1) + +## Symptom + +On a 1.68M-row store whose largest type held 586,986 rows, an equality lookup on an indexed +property of that type took 82–366 ms, and a lookup for a missing key 310 ms. The same query +with correct statistics takes 0–1 ms. Results were identical in every case; only speed +changed. Stores upgraded from 4.4.2, whose indexes are the legacy non-partial shape, were +not affected. + +## Why + +All objects share `JsonValue (Key, FullTypeName, Partition, Data)` with the general index +`idx_jsonvalue_fulltypename_partition (FullTypeName, Partition)`. 5.x `CreateIndex` adds a +per-type partial index: + +```sql +CREATE INDEX idx_GroupId_WideModel_0badcafe +ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) +WHERE FullTypeName = 'Zzz.Models.WideModel'; +``` + +Two places gathered statistics with `PRAGMA analysis_limit = 400`: `Tycho.RunOptimize` +(`PRAGMA analysis_limit = 400; PRAGMA optimize;` on connect, disconnect and dispose) and +`Queries.AnalyzeBounded` (`PRAGMA analysis_limit = 400; ANALYZE;` after `CreateIndex`). +With a limit, `ANALYZE` reads only the first ~400 entries of each index: + +- The general index is ordered by type name, and the types that sort first are tiny + (22, 112, 10, 202 rows… in the real store). Its sample spans a handful of types, so + `sqlite_stat1` credits every type with ~81 rows. The real type has 586,986. +- The partial index is ordered by `(Partition, GroupId)`, so its sample sits inside one key + and credits every key with ~401 rows. The truth is ~542 across 1,083 keys. + +The planner compares 81 against 401 and chooses the general index, then reads and +JSON-parses every row of the type on each lookup. Full statistics (`586986 586986 542` +against `1682261 34332 31741`) or no statistics at all keep the partial index chosen. So +does a partial index with no statistics row next to a full, stale or zero-row general-index +row, and statistics taken on a few hundred rows before 540,000 arrive (probes on the +synthetic store); the only snapshots that mislead the planner are a sampled pair, a full +partial-index row next to a stale general-index row, or a partial-index row that says one +key holds the whole index. + +Plain `PRAGMA optimize` cannot be used either: the default mask (`0xfffe`) includes bit +`0x10`, which applies a temporary 2,000-row limit regardless of `analysis_limit`. It wrote +`2001 501` against `101` and mis-ranked the indexes the same way. + +The bundled SQLite is 3.50.4 (`SQLitePCLRaw.bundle_e_sqlite3` 3.0.1) and 3.39.2 for the +Encrypted package (`bundle_e_sqlcipher` 2.1.10). Both are affected: the explicit `ANALYZE` +behaves identically, and the regression tests fail on both. + +## Repro + +- `docs/planner-statistics-sampling.sql` — sqlite3 CLI only, synthetic data, ~3 s. Forty + tiny types that sort first, one type with 540,000 rows over 1,000 keys, the same partial + index shape. Output on SQLite 3.51.0: + + | State | `sqlite_stat1` (partial / general) | Plan | Lookup | + |---|---|---|---| + | `analysis_limit = 400; ANALYZE` (stock 5.3.1) | `540000 401 401` / `543990 81 81` | general index | 196–217 ms, missing key 205 ms | + | `analysis_limit = 0; ANALYZE` | `540000 540000 540` / `543990 13269 13269` | partial index | 0–1 ms | + | no statistics | — | partial index | 0–1 ms | + | `PRAGMA optimize` (default mask), `analysis_limit = 0` | `540000 2001 501` / `543990 101 101` | general index | 220 ms | + | `PRAGMA optimize(0x10002)` | `540000 540000 540` / `543990 13269 13269` | partial index | 1 ms | + + Two more cases that shaped the fix: sampled rows already in the file are left alone by + `PRAGMA optimize(0x10002)` (nothing is missing, nothing grew), and a full row for the + partial index next to a sampled row for the general index still picks the general index. + +- `TychoDB.UnitTests/PlannerStatisticsTests.cs` — three tests through Tycho's own + `CreateIndexAsync`, `ConnectAsync` and dispose paths on a 20,400-row store (40 small + types, one type with 20,000 rows over 200 keys). Each asserts the plan for the library's + own filter SQL uses the partial index and that its statistics row reads from the whole + index (`20000 20000 100`). On 5.3.1 all three fail in both configurations with + `SEARCH JsonValue USING INDEX idx_jsonvalue_fulltypename_partition`. On the same + Tycho-written file, 5.3.1's statement leaves `20000 401 81` / `20400 10 10` and a lookup + takes 7–11 ms; the fixed build leaves `20000 20000 100` / `20400 498 498` and 0.03 ms. + +Bound parameters are fine in the library: SQLite re-plans when a bound value touches a +partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic +plan. The tests bind the parameters; the CLI script uses literals. + +## Fix + +- `Tycho.RunOptimize` runs `PRAGMA optimize(0x10002)` with no `analysis_limit`, at connect + and at disconnect/dispose alike. `0x10002` is SQLite's documented form for a long-lived + connection at open: check every table, re-analyze those whose indexes lack statistics or + whose row count moved by an order of magnitude, and leave out bit `0x10`. The disconnect + call needs the same mask; the default mask's 2,000-row cap reproduces the problem. +- After `CreateIndex`, `Queries.Analyze` runs `PRAGMA analysis_limit = 0; ANALYZE;`. It is + a full `ANALYZE`, not `ANALYZE `: a full row next to a sampled or stale row + for the general index still mis-ranks. It is an explicit `ANALYZE`, not `PRAGMA optimize`: + on 3.39.2 `optimize` only considers tables the planner has used on the connection, so it + would do nothing right after `CREATE INDEX`. +- A store written by an earlier 5.x release already holds sampled rows, which + `optimize(0x10002)` never revisits (repro case 6). On its first connect, Tycho runs one + full `ANALYZE` and stamps the store with `PRAGMA user_version = 1` (unused by Tycho until + now); later connects use `optimize(0x10002)`. +- `autoOptimize: false` connects without the one-time upgrade work — the four + `DROP INDEX IF EXISTS` for the indexes 4.x created (now `Queries.DropLegacyIndexes`, + appended to the connect script only when the option is on) and the statistics step above + — and skips the `ANALYZE` after `CreateIndex`; a new index without a statistics row is + chosen by default heuristics until its row arrives. `Optimize`/`OptimizeAsync` do exactly + what connect skipped: the drops, then the same conditional statistics step, so a call + with nothing to do costs ~0 ms and the app can run it on every launch. The drops stay: + they are what makes bulk writes 25–45% faster, and nothing else is removed. Disconnect + still runs `optimize(0x10002)` in both modes. +- README and CHANGELOG describe the new behavior. + +## Cost + +| Store | Sampled `ANALYZE` | Full `ANALYZE` | +|---|---|---| +| synthetic, 544k rows (CLI) | 0.017 s | 0.13–0.26 s | +| real, 1.68M rows, fresh | 2.9 s | 3.2 s | +| real, 2.2 GB, upgraded from 4.4.2 | — | 17.5 s | + +The full `ANALYZE` runs after each new index, as before. `PRAGMA optimize(0x10002)` runs +`ANALYZE` only when an index has no statistics or a table's row count moved tenfold, and is +otherwise a no-op (0.000 s measured), so the connect-time cost is paid once per store, not +per launch. SQLite before 3.46 — the Encrypted package's 3.39.2 — ignores the `0x10000` +bit and lets `PRAGMA optimize` consider only tables the connection's planner has used, so +a probe read of `JsonValue` precedes the pragma; without it a fresh connection analyzed +nothing there, which the opt-out test caught on the Encrypted build. + +## Decisions + +1. **Stores that already hold 5.3.1's sampled rows** are repaired once at connect: nothing + is missing and nothing grew, so `PRAGMA optimize(0x10002)` would leave them, and + re-declaring an unchanged index runs no `ANALYZE`; without the repair they would stay slow + until a table grew tenfold or an index changed. The repair costs one full `ANALYZE` per + existing store and is on by default. +2. **The connect-time work blocks the first launch of an upgraded store.** The `ANALYZE` + costs the 3.2 s / 17.5 s above the first time it runs on a store with no statistics (a + 4.x upgrade), one written by an earlier release, or one that grew tenfold. The four + legacy index drops were most of a 10–30 s stall MoveScoutPro measured on a large + upgraded store (main-thread samples in `sqlite3BtreeDropTable`/`clearDatabasePage`): + freeing an index's pages is proportional to its size, and with `secure_delete` on — + SQLCipher's default — every freed page is written back. On the 165 MB synthetic store, + dropping three ~15 MB legacy indexes took 6–7 ms each plain and 39–54 ms each with + `secure_delete`, in both auto-vacuum modes. Both stay on by default, with + `autoOptimize: false` as the opt-out and `Optimize`/`OptimizeAsync` for the app to run + them when convenient — before a large download for the drops (faster writes), after it + for the statistics (fresh plans), never during it. They hold the single connection for + the duration (17–24 s on the 2.2 GB store the first time, ~0 ms afterwards) and run on + the calling thread — Microsoft.Data.Sqlite executes synchronously, so the async form + alone does not move the work off the caller — so apps call them from a background + thread. The disconnect-time `optimize(0x10002)` is not affected by the opt-out. + `CreateIndex` itself drops a per-type legacy index and builds the partial one, which is + the third piece of an upgrade stall and already under the app's control through when it + calls it. +3. **Review outcomes.** The opted-out `CreateIndex` no longer analyzes (an opted-out app + declaring N indexes would otherwise pay N full analyzes, ~2× each while the legacy + indexes survive); `user_version` is stamped only when lower, so a higher store version + is never clobbered; `OptimizeAsync` stays inline like every other async method, with the + threading caveat documented. Not changed: disconnect stays automatic (a mid-`ANALYZE` + kill rolls back and the next disconnect retries), and the opted-out connect skips + `optimize(0x10002)` entirely — on a stamped store it is usually a no-op, but when it is + not it is the multi-second `ANALYZE` the opt-out exists to avoid, and the launch-page + `Optimize` covers it. +4. **Known limitation.** The stamp is never invalidated, so if a 5.3.1-or-earlier build + writes to the store after 5.3.2 has stamped it, its sampled rows return and nothing + detects them; `Optimize` sees a stamped store with nothing missing and nothing grown. + Downgrades are out of scope; a `force` flag on `Optimize` would be the remedy if it is + ever needed. + +## Considered and not done + +Taking the choice away from the planner — a `+FullTypeName` term or `INDEXED BY` in the +generated SQL whenever a partial index applies — would make index choice independent of +statistics. It was not done: `+FullTypeName` would turn every filter on an unindexed +property into a scan of all types, SQLite documents `INDEXED BY` as a regression-testing +aid rather than a tuning tool, and the query builder would have to know which partial +indexes exist. The planner also does not need the help when statistics are consistent: a +partial index with no statistics row is chosen against a full, stale or sampled row for +the general index. The general index wins only when both rows were sampled, or when the +partial row is full and the general row stale — the inconsistent states, which the fix +removes by never sampling and never refreshing one index without the others. + +## Verification + +- Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and + Encrypted (3.39.2). +- New tests on 5.3.1: 3 failed in both configurations. With the fix: 3 passed in both. +- The change lands as four code commits, each building and passing the Debug suite on its + own: the core fix (3 tests, 365 passed); the first-connect repair of sampled stores and + the never-lowered `user_version` stamp (2 tests, 367); the `autoOptimize` opt-out with + `Optimize`/`OptimizeAsync` (5 tests, 372 — including one that observes, through a + non-persistent connection, that an opted-out `CreateIndex` leaves no statistics row and + the partial index is chosen anyway, and that `Optimize` then fills it in; and one in + `IndexDdlTests` showing the opt-out keeps the legacy indexes until `Optimize` drops + them); and the probe read that makes `PRAGMA optimize` consider `JsonValue` on SQLite + 3.39.2, which that observing test caught on the Encrypted build. +- Final state: 372 passed, 4 skipped, 0 failed in both configurations (Debug 2 s, + Encrypted 1 m 26 s). diff --git a/docs/planner-statistics-sampling.sql b/docs/planner-statistics-sampling.sql new file mode 100644 index 0000000..3506b7f --- /dev/null +++ b/docs/planner-statistics-sampling.sql @@ -0,0 +1,172 @@ +-- Sampled ANALYZE (PRAGMA analysis_limit = 400) makes SQLite prefer the general +-- (FullTypeName, Partition) index over a per-type partial expression index. +-- +-- Usage: rm -f repro.db repro.db-wal repro.db-shm; sqlite3 repro.db < analyze-sampling-repro.sql +-- Needs only the sqlite3 CLI (PRAGMA optimize(0x10002) needs 3.46+; written against 3.51.0). +-- Every row is generated below; no application database is read. Runs in about 3 s. +-- +-- Expected: [1] and [4] choose idx_jsonvalue_fulltypename_partition and take ~0.2 s per +-- lookup; [2], [3] and [5] choose the partial index and take ~0.001 s. [6] shows that +-- optimize(0x10002) leaves already-sampled statistics alone; [7] that a full row for the +-- partial index alone does not help while the general index's row is still sampled. + +.bail on +.mode list +.headers off + +PRAGMA journal_mode = WAL; +PRAGMA synchronous = OFF; + +CREATE TABLE JsonValue +( + Key TEXT NOT NULL, + FullTypeName TEXT NOT NULL, + Partition TEXT NOT NULL, + Data JSON NOT NULL, + PRIMARY KEY (Key, FullTypeName, Partition) +); +CREATE INDEX idx_jsonvalue_fulltypename_partition ON JsonValue (FullTypeName, Partition); + +.print +.print '== Seed: 40 tiny types whose names sort first (10-199 rows each), then one wide' +.print ' type with 540,000 rows over 1,000 distinct GroupId values (540 rows per key).' + +WITH RECURSIVE + t(n) AS (SELECT 0 UNION ALL SELECT n + 1 FROM t WHERE n < 39), + r(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM r WHERE i < 198) +INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) +SELECT 'small-' || i, printf('Aaa.Small%02d', n), '', json_object('Id', i, 'Name', 'small ' || i) +FROM t JOIN r ON i < 10 + ((n * 37) % 190); + +WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM s WHERE i < 539999) +INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) +SELECT 'wide-' || i, 'Zzz.Models.WideModel', '', + json_object('GroupId', printf('G%04d', i % 1000), 'Seq', i, 'Label', 'row ' || i) +FROM s; + +SELECT 'first types in index order: ' || group_concat(FullTypeName || '=' || c, ', ') +FROM (SELECT FullTypeName, count(*) AS c FROM JsonValue GROUP BY 1 ORDER BY 1 LIMIT 6); +SELECT 'total rows: ' || count(*) FROM JsonValue; +SELECT 'wide rows: ' || count(*) || ', distinct GroupId: ' || count(DISTINCT JSON_EXTRACT(Data, '$.GroupId')) +FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel'; + +-- The shape TychoDB 5.x CreateIndex produces. +CREATE INDEX idx_GroupId_WideModel_0badcafe +ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) +WHERE FullTypeName = 'Zzz.Models.WideModel'; + +-- --------------------------------------------------------------------------- +.print +.print '== [1] Sampled statistics, as 5.3.1 writes them: PRAGMA analysis_limit = 400; ANALYZE;' +.timer on +PRAGMA analysis_limit = 400; +ANALYZE; +.timer off +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.print '-- lookups (rows found | bytes read), then time:' +.timer on +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0007'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0993'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'missing'); +.timer off + +-- --------------------------------------------------------------------------- +.print +.print '== [2] Full statistics: PRAGMA analysis_limit = 0; ANALYZE;' +.timer on +PRAGMA analysis_limit = 0; +ANALYZE; +.timer off +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.print '-- lookups:' +.timer on +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0007'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0993'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'missing'); +.timer off + +-- --------------------------------------------------------------------------- +.print +.print '== [3] No statistics: DELETE FROM sqlite_stat1; ANALYZE sqlite_master;' +DELETE FROM sqlite_stat1; +ANALYZE sqlite_master; +SELECT 'stat1 rows: ' || count(*) FROM sqlite_stat1; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.print '-- lookups:' +.timer on +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0007'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0993'); +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'missing'); +.timer off + +-- --------------------------------------------------------------------------- +.print +.print '== [4] Plain PRAGMA optimize from no statistics, even with analysis_limit = 0:' +.print ' the default mask (bit 0x10) caps the ANALYZE it runs at 2,000 rows per index.' +PRAGMA analysis_limit = 0; +PRAGMA optimize; +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.timer on +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.timer off + +-- --------------------------------------------------------------------------- +.print +.print '== [5] PRAGMA optimize(0x10002) from no statistics: full ANALYZE of every table.' +DELETE FROM sqlite_stat1; +ANALYZE sqlite_master; +.print '-- what it would run (0x10003 = same mask plus the debug bit):' +PRAGMA optimize(0x10003); +.timer on +PRAGMA optimize(0x10002); +.timer off +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.timer on +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.timer off +.print '-- a second optimize(0x10002) with statistics already present does nothing:' +PRAGMA optimize(0x10003); +.timer on +PRAGMA optimize(0x10002); +.timer off + +-- --------------------------------------------------------------------------- +.print +.print '== [6] A store that already holds the sampled statistics 5.3.1 writes, then optimize(0x10002):' +.print ' nothing is missing and nothing grew, so the sampled rows stay.' +PRAGMA analysis_limit = 400; +ANALYZE; +PRAGMA analysis_limit = 0; +.print '-- what it would run:' +PRAGMA optimize(0x10003); +PRAGMA optimize(0x10002); +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); + +-- --------------------------------------------------------------------------- +.print +.print '== [7] Mixed: sampled row for the general index, full row for the partial index only.' +DELETE FROM sqlite_stat1; +ANALYZE sqlite_master; +PRAGMA analysis_limit = 400; +ANALYZE idx_jsonvalue_fulltypename_partition; +PRAGMA analysis_limit = 0; +.timer on +ANALYZE idx_GroupId_WideModel_0badcafe; +.timer off +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); From dbef355aca78b3af2a68f6e6d3b5130c11256eb5 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 10 Oct 2026 00:50:46 -0500 Subject: [PATCH 06/25] fix: derive the user_version stamp from its constant The stamp SQL hard-coded the value GatherStatistics compared against, so bumping one without the other would have made every connect and Optimize run a full ANALYZE. One literal now feeds both. Also note, above the analyze step in ExecuteCreateIndex, that an opted-out index gets its statistics at Optimize or at the next Disconnect, whichever comes first. --- TychoDB.UnitTests/PlannerStatisticsTests.cs | 9 ++++++--- TychoDB/Queries.cs | 7 ++++--- TychoDB/Tycho.cs | 10 +++++++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 1370165..c8e8358 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -45,6 +45,9 @@ public class PlannerStatisticsTests private static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); + private static readonly long StampedUserVersion = + long.Parse(Queries.FullStatisticsUserVersion, System.Globalization.CultureInfo.InvariantCulture); + public class WideModel { public string Key { get; set; } @@ -148,7 +151,7 @@ public async Task Connect_RepairsSampledStatisticsLeftByAnEarlierRelease() (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - ReadUserVersion(dbFile).ShouldBe((long)Queries.FullStatisticsUserVersion); + ReadUserVersion(dbFile).ShouldBe(StampedUserVersion); AssertPartialIndexChosen(dbFile); } @@ -192,7 +195,7 @@ public async Task Connect_WithAutoOptimizeOff_LeavesStatisticsUntilOptimizeIsCal (await db.OptimizeAsync()).ShouldBeTrue(); } - ReadUserVersion(dbFile).ShouldBe((long)Queries.FullStatisticsUserVersion); + ReadUserVersion(dbFile).ShouldBe(StampedUserVersion); AssertPartialIndexChosen(dbFile); } @@ -210,7 +213,7 @@ public async Task Optimize_OnStoreFromAnEarlierRelease_GathersFullStatistics() db.Optimize(); } - ReadUserVersion(dbFile).ShouldBe((long)Queries.FullStatisticsUserVersion); + ReadUserVersion(dbFile).ShouldBe(StampedUserVersion); AssertPartialIndexChosen(dbFile); } diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 5b5a206..ea8619d 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -586,12 +586,13 @@ public static string DropIndex(string fullIndexName) // once. A store written by an earlier 5.x release reads 0 and may hold sampled // rows, which PRAGMA optimize never revisits (nothing is missing and nothing has // grown), so the first connect runs Analyze instead of PragmaOptimize. Written - // only when the stored value is lower, so a higher version is never lowered. - public const int FullStatisticsUserVersion = 1; + // only when the stored value is lower, so a higher version is never lowered. The + // literal is the single source of both the stamp and the value compared against. + public const string FullStatisticsUserVersion = "1"; public const string UserVersion = "PRAGMA user_version;"; - public const string StampFullStatistics = "PRAGMA user_version = 1;"; + public const string StampFullStatistics = "PRAGMA user_version = " + FullStatisticsUserVersion + ";"; // SQLite's recommended form for a long-lived connection: check every table and // re-analyze those that need it, without the temporary analysis_limit the default diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 30da506..ba7eea7 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -36,6 +36,9 @@ private const string /// private const int IndexShapeVersion = 2; + private static readonly long FullStatisticsUserVersion = + long.Parse(Queries.FullStatisticsUserVersion, System.Globalization.CultureInfo.InvariantCulture); + // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); @@ -380,7 +383,7 @@ private static void GatherStatistics(SqliteConnection connection) command.CommandText = Queries.UserVersion; long userVersion = command.ExecuteScalar() is long version ? version : 0L; - if (userVersion < Queries.FullStatisticsUserVersion) + if (userVersion < FullStatisticsUserVersion) { command.CommandText = Queries.Analyze; command.ExecuteNonQuery(); @@ -2356,8 +2359,9 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de // Refresh planner statistics outside the transaction so the index just // created is usable by the very next query rather than only after a // Disconnect. Advisory: a failure here must not fail index creation. An - // instance that opted out of automatic maintenance leaves this to Optimize; - // until then the planner estimates the new index by default heuristics, + // instance that opted out of automatic maintenance skips this; its new index + // gets statistics at Optimize or at the next Disconnect, whichever comes + // first, and until then the planner estimates it by default heuristics, // which still favor it. if (analyze) { From ed0da4b43099dd38196c211c6a9420e69ac7ad4f Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 10 Oct 2026 03:45:58 -0500 Subject: [PATCH 07/25] fix: decide statistics staleness from an exact row count, not PRAGMA optimize PRAGMA optimize's tenfold check estimates a table's row count from the cell counts down the leftmost path of its b-tree. A few large documents at the lowest rowids leave that leaf nearly empty and the estimate an order of magnitude low, so a 2.2 GB production store (1.84M rows, estimated at 174,370) was re-analyzed on every connect, disconnect and Optimize(), 20-30 s each, although every index had full, current statistics. Reproduced with three 3 KB documents before 540k small rows. Connect, disconnect and Optimize() now re-analyze only when an index of JsonValue has no sqlite_stat1 row or the exact count(*) differs tenfold from the row count recorded in the general index's row; the count is a scan of the covering general index, 36 ms on 1.8M rows. This also makes the probe read for SQLite 3.39.2 unnecessary. --- CHANGELOG.md | 37 ++-- README.md | 5 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 194 +++++++++++++++++--- TychoDB/Queries.cs | 45 +++-- TychoDB/Tycho.cs | 116 ++++++++---- docs/planner-statistics-row-estimate.sql | 76 ++++++++ docs/planner-statistics-sampling.md | 78 +++++--- 7 files changed, 426 insertions(+), 125 deletions(-) create mode 100644 docs/planner-statistics-row-estimate.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 69bd675..518b659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,21 +16,21 @@ missing key, against 0–1 ms with full statistics or none at all. Results were identical throughout; only speed changed. Statistics are no longer sampled: `CreateIndex` runs a full `ANALYZE` (analyzing the new index alone would mix a full row with whatever the other - indexes hold and can mis-rank them the same way), and connect/disconnect run - `PRAGMA optimize(0x10002)`, SQLite's documented form for long-lived connections. It checks - every table and re-analyzes those whose statistics are missing or whose row count moved - by an order of magnitude, without the temporary analysis limit the default form applies - (plain `PRAGMA optimize`, even after `analysis_limit = 0`, capped at 2,000 rows and - mis-ranked the indexes the same way); once statistics are current it is a no-op. A full - `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on an upgraded 2.2 GB store. - A store written by an earlier 5.x release already holds sampled rows, which - `PRAGMA optimize` never revisits (nothing is missing and nothing has grown), so the first - connect of such a store runs one full `ANALYZE` and stamps it with `PRAGMA user_version = 1` - (a higher value is never lowered). If an earlier release writes to the store after that, - its sampled rows return and are not detected. On the Encrypted package (SQLite 3.39.2, - which lets `PRAGMA optimize` consider only tables the connection has already queried), a - probe read precedes the pragma so that connect, disconnect and `Optimize` behave the same - as on the plain build. + indexes hold and can mis-rank them the same way), and connect and disconnect run a full + `ANALYZE` when an index of `JsonValue` has no statistics or the table's exact row count + has moved tenfold since they were gathered — otherwise nothing. SQLite's own + `PRAGMA optimize` was tried first and rejected twice over: its default form caps the + analysis at 2,000 rows (plain `PRAGMA optimize`, even after `analysis_limit = 0`, wrote + `2001 501` against `101` and mis-ranked the indexes the same way), and its tenfold check + estimates the row count from the cell counts down the leftmost path of the table's + b-tree, which a few large documents at the lowest rowids make an order of magnitude + wrong: a 2.2 GB production store (1.84M rows, estimated at 174,370) was re-analyzed on + every call, 20–30 s each. The exact count is a scan of the covering general index, 36 ms + on 1.8M rows. A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on the 2.2 GB + store. A store written by an earlier 5.x release already holds sampled rows, which look + complete and current, so the first connect of such a store runs one full `ANALYZE` and + stamps it with `PRAGMA user_version = 1` (a higher value is never lowered). If an earlier + release writes to the store after that, its sampled rows return and are not detected. ### Added @@ -44,12 +44,13 @@ without the `ANALYZE` after `CreateIndex` (a new index is chosen by default heuristics until its statistics arrive); then call `Optimize()` or `OptimizeAsync()` when convenient — on a loading page, for example. They do exactly the work connect skipped: the drops, - then a full `ANALYZE` on a store written by an earlier release or `PRAGMA optimize(0x10002)` - otherwise, so a call with nothing to do costs ~0 ms. They hold the single connection for the + then a full `ANALYZE` on a store written by an earlier release, when an index has no + statistics, or when the row count moved tenfold — otherwise nothing, so a call with nothing + to do costs an exact row count (36 ms on 1.8M rows). They hold the single connection for the duration, so every other operation on the instance waits (17–24 s on the 2.2 GB store), and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not move the work off the caller — so call them from a background thread. The - disconnect-time `PRAGMA optimize` is unaffected by the opt-out. + disconnect-time check is unaffected by the opt-out. ## 5.3.1 — 2026-10-05 diff --git a/README.md b/README.md index fe5b7d1..eb8fe58 100644 --- a/README.md +++ b/README.md @@ -497,8 +497,9 @@ This matters for how they behave: the old one, and indexes created by older versions are migrated away automatically. Declaring your indexes on every app launch is the intended usage. - **Statistics are refreshed** with a full `ANALYZE` after an index is created, so a - new index is usable by the very next query, and `PRAGMA optimize(0x10002)` runs on - connect and disconnect to re-analyze tables whose statistics are missing or stale. + new index is usable by the very next query, and connect and disconnect re-analyze + when an index has no statistics or the row count has moved tenfold since they were + gathered. A store written by 5.3.1 or earlier gets one full `ANALYZE` on its first connect, to replace the sampled statistics those versions wrote. Statistics are never sampled: a sample of the type-ordered general index sees only the smallest types and would make diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index c8e8358..6a12cf1 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -43,6 +43,11 @@ public class PlannerStatisticsTests private const string IndexName = "group_idx"; private const string LookupGroup = "G0042"; + // Documents large enough that each fills a leaf page of its own. Stored first, they + // occupy the lowest rowids and the leftmost leaf of the table's b-tree. + private const int LargeDocumentCount = 8; + private const int LargeDocumentPayloadLength = 3000; + private static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); private static readonly long StampedUserVersion = @@ -57,6 +62,13 @@ public class WideModel public int Seq { get; set; } } + public class LargeModel + { + public string Key { get; set; } + + public string Payload { get; set; } + } + [TestMethod] public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexStaysChosen() { @@ -265,6 +277,89 @@ public async Task CreateIndex_WithAutoOptimizeOff_LeavesStatisticsToOptimize() AssertPartialIndexChosen(dbFile); } + [TestMethod] + public async Task Connect_WithLargeDocumentsFirst_DoesNotGatherStatisticsEveryLaunch() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(LargeDocuments(), x => x.Key); + await db.WriteObjectsAsync(WideRows(), x => x.Key); + await db.CreateIndexAsync(x => x.GroupId, IndexName); + } + +#if !ENCRYPTED + // SQLite 3.46+ estimates the row count from the cell counts down the leftmost + // path of the b-tree; the large documents make that estimate an order of + // magnitude low, so its PRAGMA optimize would re-analyze on every connect. + SqliteWouldReanalyze(dbFile).ShouldBeTrue(); +#endif + + PlantSentinelStatRow(dbFile); + + for (int launch = 0; launch < 2; launch++) + { + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + } + + HasSentinelStatRow(dbFile).ShouldBeTrue(); + AssertPartialIndexChosen(dbFile); + } + + [TestMethod] + public async Task Connect_GathersStatisticsAgain_OnlyAfterTenfoldGrowth() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + PlantSentinelStatRow(dbFile); + + // Six times the rows: not enough. + SeedWideRowsDirectly(dbFile, WideRowCount, 5 * WideRowCount); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + HasSentinelStatRow(dbFile).ShouldBeTrue(); + + // Eleven times the rows: statistics are gathered again, over everything. + SeedWideRowsDirectly(dbFile, 6 * WideRowCount, 5 * WideRowCount); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + HasSentinelStatRow(dbFile).ShouldBeFalse(); + ReadStat(dbFile, ReadPhysicalIndexName(dbFile)) + .ShouldBe($"{11 * WideRowCount} {11 * WideRowCount} {11 * RowsPerGroup}"); + } + + [TestMethod] + public async Task Connect_GathersStatisticsAgain_AfterTenfoldShrink() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + await SeedIndexedStore(path, dbName); + PlantSentinelStatRow(dbFile); + DeleteWideRowsFrom(dbFile, WideRowCount / 20); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + HasSentinelStatRow(dbFile).ShouldBeFalse(); + ReadStat(dbFile, ReadPhysicalIndexName(dbFile)) + .ShouldBe($"{WideRowCount / 20} {WideRowCount / 20} {RowsPerGroup / 20}"); + } + // ---------- assertions ---------- private static void AssertPartialIndexChosen(string dbFile) { @@ -366,6 +461,48 @@ private static bool HasStatTable(SqliteConnection conn) return command.ExecuteScalar() is not null; } + private static bool SqliteWouldReanalyze(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + + command.CommandText = "SELECT 1 FROM JsonValue WHERE FullTypeName = '' AND Partition = '' LIMIT 1"; + command.ExecuteScalar(); + + command.CommandText = "PRAGMA optimize(0x10003)"; + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + if (reader.GetString(0).Contains("ANALYZE", StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + + /// + /// A whole-database ANALYZE empties sqlite_stat1 before rewriting it, so this row + /// survives only if none ran. It names StreamValue because SQLite reads a row whose + /// index it does not know as that table's row count, which must not touch JsonValue. + /// + private static void PlantSentinelStatRow(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES ('StreamValue', 'idx_sentinel', '1 1')"; + command.ExecuteNonQuery(); + } + + private static bool HasSentinelStatRow(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT count(*) FROM sqlite_stat1 WHERE idx = 'idx_sentinel'"; + return (long)command.ExecuteScalar() == 1; + } + private static long ReadUserVersion(string dbFile) { using var conn = OpenInspection(dbFile); @@ -447,32 +584,47 @@ private static void SeedSmallTypes(string dbFile) transaction.Commit(); } - private static void SeedWideRowsDirectly(string dbFile) + private static List LargeDocuments() + { + var payload = new string('x', LargeDocumentPayloadLength); + var rows = new List(LargeDocumentCount); + for (int i = 0; i < LargeDocumentCount; i++) + { + rows.Add(new LargeModel { Key = $"large-{i}", Payload = payload }); + } + + return rows; + } + + /// Writes wide rows with the same shape as , for Seq values from..from + count - 1. + private static void SeedWideRowsDirectly(string dbFile, int from = 0, int count = WideRowCount) { using var conn = OpenInspection(dbFile); - using var transaction = conn.BeginTransaction(); using var insert = conn.CreateCommand(); - insert.Transaction = transaction; insert.CommandText = - "INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) " + - "VALUES ($key, $fullTypeName, '', json_object('Key', $key, 'GroupId', $groupId, 'Seq', $seq))"; - - var key = insert.Parameters.Add("$key", SqliteType.Text); - var fullTypeName = insert.Parameters.Add("$fullTypeName", SqliteType.Text); - var groupId = insert.Parameters.Add("$groupId", SqliteType.Text); - var seq = insert.Parameters.Add("$seq", SqliteType.Integer); - - fullTypeName.Value = typeof(WideModel).FullName; - - foreach (var row in WideRows()) - { - key.Value = row.Key; - groupId.Value = row.GroupId; - seq.Value = row.Seq; - insert.ExecuteNonQuery(); - } + """ + WITH RECURSIVE s(i) AS (SELECT $from UNION ALL SELECT i + 1 FROM s WHERE i < $from + $count - 1) + INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) + SELECT 'wide-' || i, $fullTypeName, '', + json_object('Key', 'wide-' || i, 'GroupId', 'G' || printf('%04d', i % $groups), 'Seq', i) + FROM s + """; + insert.Parameters.AddWithValue("$from", from); + insert.Parameters.AddWithValue("$count", count); + insert.Parameters.AddWithValue("$groups", GroupCount); + insert.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); + insert.ExecuteNonQuery(); + } - transaction.Commit(); + private static void DeleteWideRowsFrom(string dbFile, int seq) + { + using var conn = OpenInspection(dbFile); + using var delete = conn.CreateCommand(); + delete.CommandText = + "DELETE FROM JsonValue WHERE FullTypeName = $fullTypeName AND JSON_EXTRACT(Data, '$.Seq') >= $seq"; + delete.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); + delete.Parameters.AddWithValue("$seq", seq); + delete.ExecuteNonQuery(); } // ---------- plumbing ---------- diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index ea8619d..3a47080 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -577,34 +577,43 @@ public static string DropIndex(string fullIndexName) // Full ANALYZE: refreshes sqlite_stat1 so a newly created index is usable by the // very next query. Every index is read in full: a sample (analysis_limit) of the // type-ordered general index sees only the smallest types and makes the planner - // prefer it over the per-type partial index (see Tycho.RunOptimize). ANALYZE of - // the new index alone would mix a full row with whatever the others hold and can - // produce the same mis-ranking. + // prefer it over the per-type partial index (see Tycho.RefreshStatistics). ANALYZE + // of the new index alone would mix a full row with whatever the others hold and + // can produce the same mis-ranking. public const string Analyze = "PRAGMA analysis_limit = 0; ANALYZE;"; // PRAGMA user_version of a store whose statistics were gathered in full at least // once. A store written by an earlier 5.x release reads 0 and may hold sampled - // rows, which PRAGMA optimize never revisits (nothing is missing and nothing has - // grown), so the first connect runs Analyze instead of PragmaOptimize. Written - // only when the stored value is lower, so a higher version is never lowered. The - // literal is the single source of both the stamp and the value compared against. + // rows, which look complete and current (nothing is missing and nothing has + // grown), so the first connect runs Analyze unconditionally. Written only when the + // stored value is lower, so a higher version is never lowered. The literal is the + // single source of both the stamp and the value compared against. public const string FullStatisticsUserVersion = "1"; public const string UserVersion = "PRAGMA user_version;"; public const string StampFullStatistics = "PRAGMA user_version = " + FullStatisticsUserVersion + ";"; - // SQLite's recommended form for a long-lived connection: check every table and - // re-analyze those that need it, without the temporary analysis_limit the default - // mask (0xfffe, bit 0x10) applies. A no-op when statistics are current. - public const string PragmaOptimize = "PRAGMA optimize(0x10002);"; - - // A planned read of JsonValue, run before PragmaOptimize. SQLite before 3.46 (the - // SQLCipher build is 3.39.2) ignores the 0x10000 bit and lets PRAGMA optimize - // consider only tables the connection's planner has used, so a connection that - // has run no query yet would analyze nothing. One index probe makes every build - // behave the same. - public const string TouchJsonValue = "SELECT 1 FROM JsonValue WHERE FullTypeName = '' AND Partition = '' LIMIT 1;"; + public const string HasStatTable = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1';"; + + // Whether JsonValue's statistics need gathering again: indexes without a + // sqlite_stat1 row, the row count recorded when statistics were gathered (the + // first number of the general index's row), and the exact row count now. SQLite's + // PRAGMA optimize makes this decision from the cell counts down the leftmost path + // of the table's b-tree, which a few large documents at the lowest rowids make an + // order of magnitude wrong, so it re-analyzed such stores on every call. The exact + // count is a scan of the covering general index: 36 ms on 1.8M rows. + public const string SelectStatisticsCoverage = + """ + SELECT + (SELECT count(*) FROM sqlite_master AS m + WHERE m.type = 'index' AND m.tbl_name = 'JsonValue' + AND NOT EXISTS (SELECT 1 FROM sqlite_stat1 AS s WHERE s.idx = m.name)), + (SELECT CAST(substr(stat, 1, instr(stat || ' ', ' ') - 1) AS INTEGER) + FROM sqlite_stat1 + WHERE tbl = 'JsonValue' AND idx = 'idx_jsonvalue_fulltypename_partition'), + (SELECT count(*) FROM JsonValue); + """; public const string SelectIndexMetadata = """ diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index ba7eea7..38ecd31 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -286,7 +286,7 @@ public void Disconnect() { if (_connection is not null) { - RunOptimize(_connection); + RefreshStaleStatistics(_connection); _connection.Close(); _connection.Dispose(); _connection = null; @@ -305,7 +305,7 @@ public async ValueTask DisconnectAsync() return; } - RunOptimize(_connection); + RefreshStaleStatistics(_connection); await _connection.CloseAsync().ConfigureAwait(false); await _connection.DisposeAsync().ConfigureAwait(false); @@ -314,14 +314,12 @@ public async ValueTask DisconnectAsync() } /// - /// Runs PRAGMA optimize(0x10002) when a connection closes: it checks every - /// table, not just those already queried, and re-analyzes any whose indexes lack - /// statistics or whose row count moved by an order of magnitude, so expression - /// indexes over JSON_EXTRACT keep being chosen. Otherwise a no-op. The open-time - /// counterpart is . + /// Re-analyzes when a connection closes if says + /// so, so expression indexes over JSON_EXTRACT keep being chosen by an app that + /// grew its data this session. The open-time counterpart is + /// . /// - /// The mask leaves out the temporary analysis_limit the default form - /// applies. Statistics must be read from the whole of each index: the general + /// Statistics are always read from the whole of each index: the general /// (FullTypeName, Partition) index is ordered by type name, so a sample of /// its first few hundred entries sees only the smallest types and credits every /// type with a handful of rows, while a sample of a per-type partial index sits @@ -330,12 +328,15 @@ public async ValueTask DisconnectAsync() /// /// Best-effort: failures never block teardown. /// - private static void RunOptimize(SqliteConnection connection) + private static void RefreshStaleStatistics(SqliteConnection connection) { try { using var command = connection.CreateCommand(); - OptimizeIfNeeded(command); + if (StatisticsNeedRefresh(command)) + { + AnalyzeAndStamp(command); + } } catch { @@ -343,23 +344,14 @@ private static void RunOptimize(SqliteConnection connection) } } - private static void OptimizeIfNeeded(SqliteCommand command) - { - command.CommandText = Queries.TouchJsonValue; - command.ExecuteScalar(); - - command.CommandText = Queries.PragmaOptimize; - command.ExecuteNonQuery(); - } - /// /// Gathers planner statistics for a freshly opened connection, which covers a - /// mobile app that connects once and never cleanly disconnects. A store stamped - /// with gets the same - /// PRAGMA optimize(0x10002) as ; a store written by - /// an earlier release gets one full ANALYZE, because the sampled rows those - /// releases wrote are neither missing nor stale by SQLite's rules and would - /// otherwise persist. Best-effort: failures never block connect. + /// mobile app that connects once and never cleanly disconnects. A store written by + /// an earlier release gets one full ANALYZE and the stamp, because the + /// sampled rows those releases wrote look complete and current; a store stamped + /// with is re-analyzed only when + /// says so. Best-effort: failures never block + /// connect. /// private static void RefreshStatistics(SqliteConnection connection) { @@ -380,23 +372,67 @@ private static void RefreshStatistics(SqliteConnection connection) private static void GatherStatistics(SqliteConnection connection) { using var command = connection.CreateCommand(); - command.CommandText = Queries.UserVersion; - long userVersion = command.ExecuteScalar() is long version ? version : 0L; - if (userVersion < FullStatisticsUserVersion) + if (ReadUserVersion(command) >= FullStatisticsUserVersion && !StatisticsNeedRefresh(command)) { - command.CommandText = Queries.Analyze; - command.ExecuteNonQuery(); + return; + } - command.CommandText = Queries.StampFullStatistics; - command.ExecuteNonQuery(); + AnalyzeAndStamp(command); + } + + /// + /// True when an index of JsonValue has no sqlite_stat1 row, or the + /// exact row count differs tenfold from the count recorded when statistics were + /// gathered. SQLite's own PRAGMA optimize decides this from the cell counts + /// down the leftmost path of the table's b-tree, which a few large documents at + /// the lowest rowids make an order of magnitude wrong, so it re-analyzed such + /// stores on every call; the exact count is a scan of the covering general index. + /// + private static bool StatisticsNeedRefresh(SqliteCommand command) + { + command.CommandText = Queries.HasStatTable; + if (command.ExecuteScalar() is null) + { + return true; } - else + + command.CommandText = Queries.SelectStatisticsCoverage; + using var reader = command.ExecuteReader(); + if (!reader.Read() || reader.GetInt64(0) > 0 || reader.IsDBNull(1)) + { + return true; + } + + long recordedRows = reader.GetInt64(1); + long rows = reader.GetInt64(2); + + if (recordedRows == 0) + { + return rows > 0; + } + + return rows >= recordedRows * 10 || rows <= recordedRows / 10; + } + + private static void AnalyzeAndStamp(SqliteCommand command) + { + command.CommandText = Queries.Analyze; + command.ExecuteNonQuery(); + + if (ReadUserVersion(command) < FullStatisticsUserVersion) { - OptimizeIfNeeded(command); + command.CommandText = Queries.StampFullStatistics; + command.ExecuteNonQuery(); } } + private static long ReadUserVersion(SqliteCommand command) + { + command.CommandText = Queries.UserVersion; + return command.ExecuteScalar() is long version ? version : 0L; + } + public void Backup(SqliteConnection backupDatabaseConnection) { _connection?.BackupDatabase(backupDatabaseConnection); @@ -2722,10 +2758,10 @@ public IReadOnlyList ListIndexes() /// /// Does the maintenance connecting does on its own when autoOptimize is on: /// drops the redundant indexes earlier versions created, then gathers planner - /// statistics — a full ANALYZE on a store written by an earlier release, - /// otherwise PRAGMA optimize(0x10002), which re-analyzes only tables whose - /// indexes lack statistics or whose row count moved tenfold. With nothing to do it - /// costs ~0 ms, so calling it on every launch is fine. + /// statistics — a full ANALYZE on a store written by an earlier release, or + /// when an index has no statistics, or when the row count moved tenfold since they + /// were gathered; otherwise nothing. With nothing to do it costs an exact row count + /// (36 ms on 1.8M rows), so calling it on every launch is fine. /// /// Holds the database's single connection for the duration, so every other /// operation on this instance waits: the first run on a 2.2 GB store upgraded from @@ -3035,7 +3071,7 @@ protected virtual void Dispose(bool disposing) { if (_connection is not null) { - RunOptimize(_connection); + RefreshStaleStatistics(_connection); } _connectionGate?.Dispose(); diff --git a/docs/planner-statistics-row-estimate.sql b/docs/planner-statistics-row-estimate.sql new file mode 100644 index 0000000..825c5ad --- /dev/null +++ b/docs/planner-statistics-row-estimate.sql @@ -0,0 +1,76 @@ +-- PRAGMA optimize decides whether a table needs re-analysis from an estimate of its row +-- count: the product of the cell counts down the leftmost path of the table's b-tree. +-- A few large documents at the lowest rowids leave the leftmost leaf nearly empty, the +-- estimate lands an order of magnitude below the truth, and the pragma re-runs a full +-- ANALYZE on every call although every index has a full, current statistics row. +-- +-- Usage: rm -f estimate.db estimate.db-wal estimate.db-shm; sqlite3 estimate.db < planner-statistics-row-estimate.sql +-- Needs the sqlite3 CLI, 3.46 or later (older versions check growth only). Runs in about 3 s. +-- +-- Expected: [1] prints ANALYZE "main"."JsonValue" right after the full ANALYZE and the +-- three timed optimize(0x10002) calls each take as long as the ANALYZE did; [2] shows the +-- exact count the library uses instead, and the index it reads. + +.bail on +.mode list +.headers off + +PRAGMA journal_mode = WAL; +PRAGMA synchronous = OFF; + +CREATE TABLE JsonValue +( + Key TEXT NOT NULL, + FullTypeName TEXT NOT NULL, + Partition TEXT NOT NULL, + Data JSON NOT NULL, + PRIMARY KEY (Key, FullTypeName, Partition) +); +CREATE INDEX idx_jsonvalue_fulltypename_partition ON JsonValue (FullTypeName, Partition); + +.print +.print '== Seed: three ~3 KB documents first (the lowest rowids, one per leaf page), then' +.print ' 540,000 small rows of one type over 1,000 keys, and the partial index.' + +WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM s WHERE i < 2) +INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) +SELECT 'large-' || i, 'Aaa.LargeModel', '', json_object('Payload', replace(hex(zeroblob(1500)), '0', 'x')) +FROM s; + +WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM s WHERE i < 539999) +INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) +SELECT 'wide-' || i, 'Zzz.Models.WideModel', '', json_object('GroupId', printf('G%04d', i % 1000), 'Seq', i) +FROM s; + +CREATE INDEX idx_GroupId_WideModel_0badcafe +ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) +WHERE FullTypeName = 'Zzz.Models.WideModel'; + +-- --------------------------------------------------------------------------- +.print +.print '== [1] Full statistics, then what PRAGMA optimize thinks of them' +PRAGMA analysis_limit = 0; +.timer on +ANALYZE; +.timer off +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +SELECT 'real rows: ' || count(*) FROM JsonValue; +.print '-- optimize(0x10003) (debug) right after the full ANALYZE; nothing should be listed:' +PRAGMA optimize(0x10003); +.print '-- optimize(0x10002), three calls in a row:' +.timer on +PRAGMA optimize(0x10002); +PRAGMA optimize(0x10002); +PRAGMA optimize(0x10002); +.timer off + +-- --------------------------------------------------------------------------- +.print +.print '== [2] The exact count the library compares with the recorded row count instead' +EXPLAIN QUERY PLAN SELECT count(*) FROM JsonValue; +.timer on +SELECT count(*) FROM JsonValue; +SELECT count(*) FROM JsonValue; +.timer off +SELECT 'recorded by ANALYZE: ' || CAST(substr(stat, 1, instr(stat || ' ', ' ') - 1) AS INTEGER) +FROM sqlite_stat1 WHERE tbl = 'JsonValue' AND idx = 'idx_jsonvalue_fulltypename_partition'; diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index bde1f17..dfc388d 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -81,20 +81,21 @@ plan. The tests bind the parameters; the CLI script uses literals. ## Fix -- `Tycho.RunOptimize` runs `PRAGMA optimize(0x10002)` with no `analysis_limit`, at connect - and at disconnect/dispose alike. `0x10002` is SQLite's documented form for a long-lived - connection at open: check every table, re-analyze those whose indexes lack statistics or - whose row count moved by an order of magnitude, and leave out bit `0x10`. The disconnect - call needs the same mask; the default mask's 2,000-row cap reproduces the problem. +- At connect and at disconnect/dispose, Tycho re-analyzes when an index of `JsonValue` has + no `sqlite_stat1` row or the exact `count(*)` differs tenfold from the row count recorded + in the general index's row, and otherwise does nothing. The branch first used SQLite's + `PRAGMA optimize(0x10002)` for this (the documented form for a long-lived connection at + open, without the default mask's 2,000-row cap, which reproduces the problem); the + follow-up below explains why it was replaced. - After `CreateIndex`, `Queries.Analyze` runs `PRAGMA analysis_limit = 0; ANALYZE;`. It is a full `ANALYZE`, not `ANALYZE `: a full row next to a sampled or stale row for the general index still mis-ranks. It is an explicit `ANALYZE`, not `PRAGMA optimize`: on 3.39.2 `optimize` only considers tables the planner has used on the connection, so it would do nothing right after `CREATE INDEX`. -- A store written by an earlier 5.x release already holds sampled rows, which - `optimize(0x10002)` never revisits (repro case 6). On its first connect, Tycho runs one - full `ANALYZE` and stamps the store with `PRAGMA user_version = 1` (unused by Tycho until - now); later connects use `optimize(0x10002)`. +- A store written by an earlier 5.x release already holds sampled rows, which look complete + and current (repro case 6). On its first connect, Tycho runs one full `ANALYZE` and stamps + the store with `PRAGMA user_version = 1` (unused by Tycho until now); later connects use + the check above. - `autoOptimize: false` connects without the one-time upgrade work — the four `DROP INDEX IF EXISTS` for the indexes 4.x created (now `Queries.DropLegacyIndexes`, appended to the connect script only when the option is on) and the statistics step above @@ -114,13 +115,10 @@ plan. The tests bind the parameters; the CLI script uses literals. | real, 1.68M rows, fresh | 2.9 s | 3.2 s | | real, 2.2 GB, upgraded from 4.4.2 | — | 17.5 s | -The full `ANALYZE` runs after each new index, as before. `PRAGMA optimize(0x10002)` runs -`ANALYZE` only when an index has no statistics or a table's row count moved tenfold, and is -otherwise a no-op (0.000 s measured), so the connect-time cost is paid once per store, not -per launch. SQLite before 3.46 — the Encrypted package's 3.39.2 — ignores the `0x10000` -bit and lets `PRAGMA optimize` consider only tables the connection's planner has used, so -a probe read of `JsonValue` precedes the pragma; without it a fresh connection analyzed -nothing there, which the opt-out test caught on the Encrypted build. +The full `ANALYZE` runs after each new index, as before. Connect, disconnect and `Optimize` +run it only when an index has no statistics or the exact row count moved tenfold; otherwise +they cost the exact count, a scan of the covering general index (36 ms warm on 1.8M rows), +so the analysis is paid once per store, not per launch. ## Decisions @@ -144,25 +142,50 @@ nothing there, which the opt-out test caught on the Encrypted build. the duration (17–24 s on the 2.2 GB store the first time, ~0 ms afterwards) and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so the async form alone does not move the work off the caller — so apps call them from a background - thread. The disconnect-time `optimize(0x10002)` is not affected by the opt-out. - `CreateIndex` itself drops a per-type legacy index and builds the partial one, which is - the third piece of an upgrade stall and already under the app's control through when it - calls it. + thread. The disconnect-time check is not affected by the opt-out. `CreateIndex` itself + drops a per-type legacy index and builds the partial one, which is the third piece of an + upgrade stall and already under the app's control through when it calls it. 3. **Review outcomes.** The opted-out `CreateIndex` no longer analyzes (an opted-out app declaring N indexes would otherwise pay N full analyzes, ~2× each while the legacy indexes survive); `user_version` is stamped only when lower, so a higher store version is never clobbered; `OptimizeAsync` stays inline like every other async method, with the threading caveat documented. Not changed: disconnect stays automatic (a mid-`ANALYZE` - kill rolls back and the next disconnect retries), and the opted-out connect skips - `optimize(0x10002)` entirely — on a stamped store it is usually a no-op, but when it is - not it is the multi-second `ANALYZE` the opt-out exists to avoid, and the launch-page - `Optimize` covers it. + kill rolls back and the next disconnect retries), and the opted-out connect skips the + statistics check entirely — when it is not a no-op it is the multi-second `ANALYZE` the + opt-out exists to avoid, and the launch-page `Optimize` covers it. 4. **Known limitation.** The stamp is never invalidated, so if a 5.3.1-or-earlier build writes to the store after 5.3.2 has stamped it, its sampled rows return and nothing detects them; `Optimize` sees a stamped store with nothing missing and nothing grown. Downgrades are out of scope; a `force` flag on `Optimize` would be the remedy if it is ever needed. +## Follow-up: SQLite's tenfold check + +Testing the branch against four real device stores, MoveScoutPro found one (1.84M rows, +2.2 GB) on which `PRAGMA optimize(0x10002)` ran a full `ANALYZE` on every call — 2–30 s +each, at connect and disconnect by default and at every `Optimize()` otherwise — although +every index had a full, current statistics row. The pragma's tenfold check estimates the +table's row count from the cell counts down the leftmost path of its b-tree; on that store +the path was 265 × 329 × 2 = 174,370 against 1,841,652 rows, a ratio just past the +threshold, because the lowest rowids hold large documents and the leftmost leaf has two +cells. Reproduced synthetically (`docs/planner-statistics-row-estimate.sql`): a few ~3 KB +documents inserted before 540,000 small rows make `PRAGMA optimize(0x10003)` report +`ANALYZE "main"."JsonValue"` immediately after a full `ANALYZE`, and `optimize(0x10002)` +re-runs it on every call. Any store can drift into this layout as rows are rewritten. + +Tycho now decides staleness itself and no longer calls `PRAGMA optimize`: a stamped store +is re-analyzed only when an index of `JsonValue` has no `sqlite_stat1` row or the exact +`count(*)` differs tenfold from the row count recorded in the general index's row. The +count is a scan of the covering general index, 36 ms warm on 1.8M rows. This also removed +the probe read that SQLite 3.39.2 (the Encrypted package) had needed, since that build lets +`PRAGMA optimize` consider only tables the connection's planner has already used. The +regression test stores eight large documents first, plants a sentinel `sqlite_stat1` row +(a whole-database `ANALYZE` empties the table before rewriting it), connects twice, and +checks the sentinel survived; two more tests check that the analysis does run after a +tenfold growth or shrink and not after a sixfold one. One thing learned on the way: SQLite +reads a `sqlite_stat1` row whose index it does not know as that table's row count, so the +sentinel names `StreamValue`, not `JsonValue`. + ## Considered and not done Taking the choice away from the planner — a `+FullTypeName` term or `INDEXED BY` in the @@ -190,5 +213,8 @@ removes by never sampling and never refreshing one index without the others. `IndexDdlTests` showing the opt-out keeps the legacy indexes until `Optimize` drops them); and the probe read that makes `PRAGMA optimize` consider `JsonValue` on SQLite 3.39.2, which that observing test caught on the Encrypted build. -- Final state: 372 passed, 4 skipped, 0 failed in both configurations (Debug 2 s, - Encrypted 1 m 26 s). +- Replacing `PRAGMA optimize` with Tycho's own staleness check added three tests (large + documents first; tenfold growth, with a sixfold growth as the negative; tenfold shrink) + and removed the need for the 3.39.2 probe. +- Final state: 375 passed, 4 skipped, 0 failed in both configurations (Debug 5 s, + Encrypted 1 m 36 s). From 93a0a04c4c08c10c067bafb9700233f268653f1d Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 10 Oct 2026 04:09:37 -0500 Subject: [PATCH 08/25] refactor: stop gathering planner statistics Every query shape TychoDB emits chooses the right index on SQLite's default heuristics: a partial index is credited with half the table, so the per-type index beats the general one for the property it covers whatever the data looks like. Statistics could only make that choice worse, and did in 5.3.1. Connect, Disconnect, Dispose, CreateIndex and Optimize no longer run ANALYZE or PRAGMA optimize, and the user_version stamp and the staleness check go with them. autoOptimize and Optimize now cover only the legacy index drops. --- TychoDB.Benchmarks/Diagnostics.cs | 2 +- TychoDB.UnitTests/IndexDdlTests.cs | 19 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 513 ++++---------------- TychoDB/Queries.cs | 41 -- TychoDB/Tycho.cs | 213 +------- 5 files changed, 133 insertions(+), 655 deletions(-) diff --git a/TychoDB.Benchmarks/Diagnostics.cs b/TychoDB.Benchmarks/Diagnostics.cs index 585137b..1bd9e74 100644 --- a/TychoDB.Benchmarks/Diagnostics.cs +++ b/TychoDB.Benchmarks/Diagnostics.cs @@ -74,7 +74,7 @@ public static async Task RunAsync() Console.WriteLine($"Delta vs baseline: {FormatBytes(sizeBroken - sizeBaseline)}"); Console.WriteLine(); - DumpTable(conn, "sqlite_stat1", "Planner statistics after Tycho dispose (PRAGMA optimize ran)"); + DumpTable(conn, "sqlite_stat1", "Planner statistics after Tycho dispose (expected: none)"); RunQueryPlans(conn, "Query plans WITH public-API indexes"); // ---- Phase C: synthetic per-index cost + corrected shapes ---- diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index c32ba23..4161025 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -215,7 +215,7 @@ public async Task CreateIndex_ChangedDefinition_RebuildsAndLeavesNoStaleIndex() } [TestMethod] - public async Task CreateIndex_RefreshesPlannerStatistics() + public async Task CreateIndex_GathersNoPlannerStatistics() { var (path, dbName) = NewDbPath(); @@ -225,12 +225,12 @@ public async Task CreateIndex_RefreshesPlannerStatistics() await db.CreateIndexAsync(x => x.LongProperty, "long_idx"); } - // Before this bucket sqlite_stat1 did not exist at all, so the planner ran - // on default heuristics for the life of the process. + // The planner runs on default heuristics, which favor the partial indexes; + // see PlannerStatisticsTests for why statistics would only mislead it. using var conn = OpenInspection(Path.Combine(path, dbName)); using var command = conn.CreateCommand(); - command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; - Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(1); + command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name LIKE 'sqlite_stat%'"; + Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(0); } [TestMethod] @@ -426,12 +426,9 @@ public async Task BuiltInIndexes_AreSlimmed_WithoutRegressingCoreQueries() // bare SCAN/SEARCH assertion cannot (on a small single-type table a scan is // genuinely the cheaper plan). // - // Both sides of the comparison have to run on freshly gathered statistics, so - // gather them here rather than inheriting whatever the connection's advisory - // PRAGMA optimize happened to do: that pragma's heuristics are version - // dependent, and SQLCipher's older SQLite leaves sqlite_stat1 unpopulated - // where the plain build fills it in. Without this the baseline would be a - // no-statistics plan and the comparison would not be like for like. + // Both sides of the comparison have to run on the same full statistics, which + // Tycho never gathers, so gather them here; the redundant indexes below are + // then analyzed too, and the comparison is like for like. Analyze(dbFile); var planBefore = CorePlans(dbFile); diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 6a12cf1..809ffcf 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -12,16 +12,17 @@ namespace TychoDB.UnitTests; /// -/// Proves the planner statistics TychoDB gathers keep a per-type partial index chosen -/// on a store where many small types sort ahead of one large one. +/// Proves the planner chooses the right index for every query shape TychoDB emits with no +/// planner statistics at all, and that TychoDB gathers none. /// -/// Statistics gathered with an analysis_limit read only the first few hundred -/// entries of each index. The general (FullTypeName, Partition) index is ordered -/// by type name, so its sample sees only the small types and reports a handful of rows -/// per type, while the partial index's sample sits inside one key and reports hundreds -/// of rows per key. The planner then prefers the general index and reads and parses -/// every row of the large type on each lookup. Full statistics, or none at all, keep the -/// partial index chosen. +/// Without a sqlite_stat1 row the planner credits a partial index with half the +/// table and every index with a fixed selectivity per equality column, so a per-type +/// partial index always beats the general (FullTypeName, Partition) index for the +/// property it covers, whatever the data looks like. Statistics can only make that choice +/// worse: a sample of the type-ordered general index sees only the smallest types and +/// credits every type with a handful of rows, while a sample of the partial index sits +/// inside one key and credits every key with hundreds, and the planner then reads every +/// row of the type on each lookup (5.3.1). /// /// [TestClass] @@ -32,27 +33,20 @@ public class PlannerStatisticsTests #endif // Forty tiny types whose names sort before the test namespace, then one type with - // 20,000 rows over 200 keys. The sample of the general index spans every small type; - // the sample of the partial index spans four keys. + // 20,000 rows over 200 keys: the layout on which sampled statistics mislead. private const int SmallTypeCount = 40; private const int RowsPerSmallType = 10; private const int GroupCount = 200; private const int RowsPerGroup = 100; private const int WideRowCount = GroupCount * RowsPerGroup; - private const string IndexName = "group_idx"; + private const string GroupIndexName = "group_idx"; + private const string SeqIndexName = "seq_idx"; + private const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; private const string LookupGroup = "G0042"; - // Documents large enough that each fills a leaf page of its own. Stored first, they - // occupy the lowest rowids and the leftmost leaf of the table's b-tree. - private const int LargeDocumentCount = 8; - private const int LargeDocumentPayloadLength = 3000; - private static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); - private static readonly long StampedUserVersion = - long.Parse(Queries.FullStatisticsUserVersion, System.Globalization.CultureInfo.InvariantCulture); - public class WideModel { public string Key { get; set; } @@ -60,17 +54,12 @@ public class WideModel public string GroupId { get; set; } public int Seq { get; set; } - } - public class LargeModel - { - public string Key { get; set; } - - public string Payload { get; set; } + public string Label { get; set; } } [TestMethod] - public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexStaysChosen() + public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexChosen() { var (path, dbName) = NewDbPath(); var dbFile = Path.Combine(path, dbName); @@ -84,16 +73,17 @@ public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexStaysCh using (var db = await BuildDb2(path, dbName).ConnectAsync()) { - await db.CreateIndexAsync(x => x.GroupId, IndexName); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - AssertPartialIndexChosen(dbFile); + HasStatTable(dbFile).ShouldBeFalse(); + AssertGroupLookupUsesPartialIndex(dbFile); } [TestMethod] - public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexStaysChosen() + public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() { var (path, dbName) = NewDbPath(); var dbFile = Path.Combine(path, dbName); @@ -101,7 +91,7 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexStaysChosen() // Launch 1: the app declares its index before any data exists. using (var db = await BuildDb(path, dbName).ConnectAsync()) { - await db.CreateIndexAsync(x => x.GroupId, IndexName); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); } SeedSmallTypes(dbFile); @@ -115,273 +105,131 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexStaysChosen() // Launch 3: the index is re-declared (a no-op) and queried. using (var db = await BuildDb2(path, dbName).ConnectAsync()) { - await db.CreateIndexAsync(x => x.GroupId, IndexName); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - AssertPartialIndexChosen(dbFile); + HasStatTable(dbFile).ShouldBeFalse(); + AssertGroupLookupUsesPartialIndex(dbFile); } [TestMethod] - public async Task Connect_AfterRowsArrivedUnanalyzed_GathersFullStatistics() + public async Task WithoutStatistics_EqualityUsesThePartialIndex() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); + var dbFile = await SeedIndexedStore(); - using (var db = await BuildDb(path, dbName).ConnectAsync()) - { - await db.CreateIndexAsync(x => x.GroupId, IndexName); - } + var plan = Explain(dbFile, filter: GroupFilter()); - // Rows that arrived without any connection gathering statistics for them: what - // the empty store left behind is nothing, or zeros, depending on the SQLite build. - SeedSmallTypes(dbFile); - SeedWideRowsDirectly(dbFile); - ReadStatRows(dbFile).ShouldAllBe(row => row.EndsWith(" 0 0 0", StringComparison.Ordinal)); - - using (var db = await BuildDb2(path, dbName).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - - AssertPartialIndexChosen(dbFile); + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, GroupIndexName)}", Case.Sensitive); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } [TestMethod] - public async Task Connect_RepairsSampledStatisticsLeftByAnEarlierRelease() + public async Task WithoutStatistics_RangeUsesThePartialIndex() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - await SeedIndexedStore(path, dbName); - LeaveSampledStatistics(dbFile); - ExplainGroupLookup(dbFile).ShouldContain("idx_jsonvalue_fulltypename_partition", Case.Sensitive); + var dbFile = await SeedIndexedStore(); - using (var db = await BuildDb2(path, dbName).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - - ReadUserVersion(dbFile).ShouldBe(StampedUserVersion); - AssertPartialIndexChosen(dbFile); - } - - [TestMethod] - public async Task Connect_DoesNotLowerAHigherUserVersion() - { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - await SeedIndexedStore(path, dbName); - SetUserVersion(dbFile, 7); - - using (var db = await BuildDb2(path, dbName).ConnectAsync()) - { - await db.CreateIndexAsync(x => x.Seq, "seq_idx"); - } - - ReadUserVersion(dbFile).ShouldBe(7L); - } - - [TestMethod] - public async Task Connect_WithAutoOptimizeOff_LeavesStatisticsUntilOptimizeIsCalled() - { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - await SeedIndexedStore(path, dbName); - LeaveSampledStatistics(dbFile); - - using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - - // Neither connecting nor disposing touched the sampled rows. - ReadUserVersion(dbFile).ShouldBe(0L); - ExplainGroupLookup(dbFile).ShouldContain("idx_jsonvalue_fulltypename_partition", Case.Sensitive); - - using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) - { - (await db.OptimizeAsync()).ShouldBeTrue(); - } + var plan = Explain( + dbFile, + filter: FilterBuilder.Create().Filter(FilterType.GreaterThan, x => x.Seq, WideRowCount - 1000)); - ReadUserVersion(dbFile).ShouldBe(StampedUserVersion); - AssertPartialIndexChosen(dbFile); + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", Case.Sensitive); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } [TestMethod] - public async Task Optimize_OnStoreFromAnEarlierRelease_GathersFullStatistics() + public async Task WithoutStatistics_SortWithLimitUsesThePartialIndex() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); + var dbFile = await SeedIndexedStore(); - await SeedIndexedStore(path, dbName); - LeaveSampledStatistics(dbFile); + var plan = Explain( + dbFile, + sort: SortBuilder.Create().OrderBy(SortDirection.Ascending, x => x.Seq), + top: 20); - using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) - { - db.Optimize(); - } - - ReadUserVersion(dbFile).ShouldBe(StampedUserVersion); - AssertPartialIndexChosen(dbFile); + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", Case.Sensitive); + plan.ShouldNotContain("TEMP B-TREE", Case.Sensitive); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } [TestMethod] - public async Task Optimize_WithCurrentStatistics_LeavesThemAlone() + public async Task WithoutStatistics_TwoIndexedEqualitiesUseOneOfThePartialIndexes() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); + var dbFile = await SeedIndexedStore(); - await SeedIndexedStore(path, dbName); - var before = ReadStatRows(dbFile); - before.ShouldNotBeEmpty(); + var plan = Explain( + dbFile, + filter: GroupFilter().And().Filter(FilterType.Equals, x => x.Seq, 42)); - using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + var partialIndexes = new[] { - db.Optimize(); - } + $"USING INDEX {ReadPhysicalIndexName(dbFile, GroupIndexName)}", + $"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", + }; - ReadStatRows(dbFile).ShouldBe(before, ignoreOrder: true); - AssertPartialIndexChosen(dbFile); + partialIndexes.Count(name => plan.Contains(name, StringComparison.Ordinal)).ShouldBe(1); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } [TestMethod] - public async Task CreateIndex_WithAutoOptimizeOff_LeavesStatisticsToOptimize() + public async Task WithoutStatistics_UnindexedPropertyUsesTheGeneralIndex() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); + var dbFile = await SeedIndexedStore(); - using (var db = await BuildDb(path, dbName).ConnectAsync()) - { - await db.WriteObjectsAsync(WideRows(), x => x.Key); - } + var plan = Explain( + dbFile, + filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Label, "row 7")); - SeedSmallTypes(dbFile); - - // The connection closes between operations, so the file can be inspected while - // the instance is alive. - using var detached = BuildDetachedDb(path, dbName).Connect(); - - await detached.CreateIndexAsync(x => x.GroupId, IndexName); - - var physicalName = ReadPhysicalIndexName(dbFile); - ReadStat(dbFile, physicalName).ShouldBeNull(); - ExplainGroupLookup(dbFile).ShouldContain($"USING INDEX {physicalName}", Case.Sensitive); - (await detached.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - - detached.Optimize(); - - AssertPartialIndexChosen(dbFile); + plan.ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); } [TestMethod] - public async Task Connect_WithLargeDocumentsFirst_DoesNotGatherStatisticsEveryLaunch() + public async Task WithoutStatistics_WholeTypeUsesTheGeneralIndex() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - using (var db = await BuildDb(path, dbName).ConnectAsync()) - { - await db.WriteObjectsAsync(LargeDocuments(), x => x.Key); - await db.WriteObjectsAsync(WideRows(), x => x.Key); - await db.CreateIndexAsync(x => x.GroupId, IndexName); - } + var dbFile = await SeedIndexedStore(); -#if !ENCRYPTED - // SQLite 3.46+ estimates the row count from the cell counts down the leftmost - // path of the b-tree; the large documents make that estimate an order of - // magnitude low, so its PRAGMA optimize would re-analyze on every connect. - SqliteWouldReanalyze(dbFile).ShouldBeTrue(); -#endif - - PlantSentinelStatRow(dbFile); - - for (int launch = 0; launch < 2; launch++) - { - using (var db = await BuildDb2(path, dbName).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - } - - HasSentinelStatRow(dbFile).ShouldBeTrue(); - AssertPartialIndexChosen(dbFile); - } - - [TestMethod] - public async Task Connect_GathersStatisticsAgain_OnlyAfterTenfoldGrowth() - { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - await SeedIndexedStore(path, dbName); - PlantSentinelStatRow(dbFile); - - // Six times the rows: not enough. - SeedWideRowsDirectly(dbFile, WideRowCount, 5 * WideRowCount); - - using (await BuildDb2(path, dbName).ConnectAsync()) - { - } - - HasSentinelStatRow(dbFile).ShouldBeTrue(); - - // Eleven times the rows: statistics are gathered again, over everything. - SeedWideRowsDirectly(dbFile, 6 * WideRowCount, 5 * WideRowCount); - - using (await BuildDb2(path, dbName).ConnectAsync()) - { - } - - HasSentinelStatRow(dbFile).ShouldBeFalse(); - ReadStat(dbFile, ReadPhysicalIndexName(dbFile)) - .ShouldBe($"{11 * WideRowCount} {11 * WideRowCount} {11 * RowsPerGroup}"); + Explain(dbFile).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); } [TestMethod] - public async Task Connect_GathersStatisticsAgain_AfterTenfoldShrink() + public async Task WithoutStatistics_CountUsesTheGeneralIndexWithoutReadingRows() { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - await SeedIndexedStore(path, dbName); - PlantSentinelStatRow(dbFile); - DeleteWideRowsFrom(dbFile, WideRowCount / 20); + var dbFile = await SeedIndexedStore(); - using (await BuildDb2(path, dbName).ConnectAsync()) - { - } - - HasSentinelStatRow(dbFile).ShouldBeFalse(); - ReadStat(dbFile, ReadPhysicalIndexName(dbFile)) - .ShouldBe($"{WideRowCount / 20} {WideRowCount / 20} {RowsPerGroup / 20}"); + Explain(dbFile, count: true).ShouldContain($"USING COVERING INDEX {GeneralIndexName}", Case.Sensitive); } // ---------- assertions ---------- - private static void AssertPartialIndexChosen(string dbFile) + private static void AssertGroupLookupUsesPartialIndex(string dbFile) { - var physicalName = ReadPhysicalIndexName(dbFile); - var plan = ExplainGroupLookup(dbFile); - - plan.ShouldContain($"USING INDEX {physicalName}", Case.Sensitive); - plan.ShouldNotContain("idx_jsonvalue_fulltypename_partition", Case.Sensitive); + var plan = Explain(dbFile, filter: GroupFilter()); - // (Partition, JSON_EXTRACT(...)) over every row of the type, with RowsPerGroup - // rows per key: statistics read from the whole index, not a sample of it. - ReadStat(dbFile, physicalName).ShouldBe($"{WideRowCount} {WideRowCount} {RowsPerGroup}"); + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, GroupIndexName)}", Case.Sensitive); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } private static FilterBuilder GroupFilter() => FilterBuilder.Create().Filter(FilterType.Equals, x => x.GroupId, LookupGroup); - private static string ExplainGroupLookup(string dbFile) + /// The plan for the SQL the library composes for a read with these options. + private static string Explain( + string dbFile, + FilterBuilder filter = null, + SortBuilder sort = null, + int? top = null, + bool count = false) { - var sb = new StringBuilder(Queries.SelectDataFromJsonValueWithFullTypeName); + var sb = new StringBuilder(count ? Queries.SelectCountFromJsonValueWithFullTypeName : Queries.SelectDataFromJsonValueWithFullTypeName); var parameters = new FilterParameters(); - GroupFilter().Build(sb, Serializer, parameters); + + filter?.Build(sb, Serializer, parameters); + sort?.Build(sb, Serializer); + + if (top is not null) + { + sb.AppendLine().AppendLine(Queries.Limit(top.Value)); + } using var conn = OpenInspection(dbFile); using var command = conn.CreateCommand(); @@ -409,139 +257,40 @@ private static string ExplainGroupLookup(string dbFile) return plan.ToString(); } - private static string ReadPhysicalIndexName(string dbFile) + private static string ReadPhysicalIndexName(string dbFile, string indexName) { using var conn = OpenInspection(dbFile); using var command = conn.CreateCommand(); command.CommandText = "SELECT PhysicalName FROM TychoIndex WHERE IndexName = $indexName"; - command.Parameters.AddWithValue("$indexName", IndexName); + command.Parameters.AddWithValue("$indexName", indexName); return (string)command.ExecuteScalar(); } - private static string ReadStat(string dbFile, string indexName) + private static bool HasStatTable(string dbFile) { using var conn = OpenInspection(dbFile); - if (!HasStatTable(conn)) - { - return null; - } - using var command = conn.CreateCommand(); - command.CommandText = "SELECT stat FROM sqlite_stat1 WHERE idx = $idx"; - command.Parameters.AddWithValue("$idx", indexName); - return command.ExecuteScalar() as string; - } - - private static List ReadStatRows(string dbFile) - { - var rows = new List(); - - using var conn = OpenInspection(dbFile); - if (!HasStatTable(conn)) - { - return rows; - } - - using var command = conn.CreateCommand(); - command.CommandText = "SELECT idx || ' ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue'"; - - using var reader = command.ExecuteReader(); - while (reader.Read()) - { - rows.Add(reader.GetString(0)); - } - - return rows; - } - - private static bool HasStatTable(SqliteConnection conn) - { - using var command = conn.CreateCommand(); - command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; + command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name LIKE 'sqlite_stat%'"; return command.ExecuteScalar() is not null; } - private static bool SqliteWouldReanalyze(string dbFile) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - - command.CommandText = "SELECT 1 FROM JsonValue WHERE FullTypeName = '' AND Partition = '' LIMIT 1"; - command.ExecuteScalar(); - - command.CommandText = "PRAGMA optimize(0x10003)"; - using var reader = command.ExecuteReader(); - while (reader.Read()) - { - if (reader.GetString(0).Contains("ANALYZE", StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } - - /// - /// A whole-database ANALYZE empties sqlite_stat1 before rewriting it, so this row - /// survives only if none ran. It names StreamValue because SQLite reads a row whose - /// index it does not know as that table's row count, which must not touch JsonValue. - /// - private static void PlantSentinelStatRow(string dbFile) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - command.CommandText = "INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES ('StreamValue', 'idx_sentinel', '1 1')"; - command.ExecuteNonQuery(); - } - - private static bool HasSentinelStatRow(string dbFile) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - command.CommandText = "SELECT count(*) FROM sqlite_stat1 WHERE idx = 'idx_sentinel'"; - return (long)command.ExecuteScalar() == 1; - } - - private static long ReadUserVersion(string dbFile) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - command.CommandText = "PRAGMA user_version"; - return (long)command.ExecuteScalar(); - } + // ---------- seeding ---------- - private static void SetUserVersion(string dbFile, int value) + /// A store with the wide type indexed on GroupId and Seq, and the small types ahead of it. + private static async Task SeedIndexedStore() { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - -#pragma warning disable CA2100 // A test-chosen integer literal. - command.CommandText = "PRAGMA user_version = " + value.ToString(System.Globalization.CultureInfo.InvariantCulture); -#pragma warning restore CA2100 - - command.ExecuteNonQuery(); - } + var (path, dbName) = NewDbPath(); - // ---------- seeding ---------- - private static async Task SeedIndexedStore(string path, string dbName) - { using (var db = await BuildDb(path, dbName).ConnectAsync()) { await db.WriteObjectsAsync(WideRows(), x => x.Key); - await db.CreateIndexAsync(x => x.GroupId, IndexName); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); + await db.CreateIndexAsync(x => x.Seq, SeqIndexName); } - SeedSmallTypes(Path.Combine(path, dbName)); - } - - /// Leaves what 5.3.1 left: statistics sampled at 400 rows, and no version stamp. - private static void LeaveSampledStatistics(string dbFile) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE; PRAGMA user_version = 0;"; - command.ExecuteNonQuery(); + var dbFile = Path.Combine(path, dbName); + SeedSmallTypes(dbFile); + return dbFile; } private static List WideRows() @@ -549,7 +298,7 @@ private static List WideRows() var rows = new List(WideRowCount); for (int i = 0; i < WideRowCount; i++) { - rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i }); + rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i, Label = $"row {i}" }); } return rows; @@ -584,49 +333,6 @@ private static void SeedSmallTypes(string dbFile) transaction.Commit(); } - private static List LargeDocuments() - { - var payload = new string('x', LargeDocumentPayloadLength); - var rows = new List(LargeDocumentCount); - for (int i = 0; i < LargeDocumentCount; i++) - { - rows.Add(new LargeModel { Key = $"large-{i}", Payload = payload }); - } - - return rows; - } - - /// Writes wide rows with the same shape as , for Seq values from..from + count - 1. - private static void SeedWideRowsDirectly(string dbFile, int from = 0, int count = WideRowCount) - { - using var conn = OpenInspection(dbFile); - using var insert = conn.CreateCommand(); - insert.CommandText = - """ - WITH RECURSIVE s(i) AS (SELECT $from UNION ALL SELECT i + 1 FROM s WHERE i < $from + $count - 1) - INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) - SELECT 'wide-' || i, $fullTypeName, '', - json_object('Key', 'wide-' || i, 'GroupId', 'G' || printf('%04d', i % $groups), 'Seq', i) - FROM s - """; - insert.Parameters.AddWithValue("$from", from); - insert.Parameters.AddWithValue("$count", count); - insert.Parameters.AddWithValue("$groups", GroupCount); - insert.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); - insert.ExecuteNonQuery(); - } - - private static void DeleteWideRowsFrom(string dbFile, int seq) - { - using var conn = OpenInspection(dbFile); - using var delete = conn.CreateCommand(); - delete.CommandText = - "DELETE FROM JsonValue WHERE FullTypeName = $fullTypeName AND JSON_EXTRACT(Data, '$.Seq') >= $seq"; - delete.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); - delete.Parameters.AddWithValue("$seq", seq); - delete.ExecuteNonQuery(); - } - // ---------- plumbing ---------- private static (string Path, string DbName) NewDbPath() { @@ -655,21 +361,6 @@ private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = tr #endif } - /// - /// Reopens an existing database, opted out of automatic maintenance, with a - /// connection that closes between operations and no pooling, so an inspection - /// connection can read the file while the instance is alive. - /// - private static Tycho BuildDetachedDb(string path, string dbName) - { - SqliteConnection.ClearAllPools(); -#if ENCRYPTED - return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: false, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: false, autoOptimize: false); -#else - return new Tycho(path, Serializer, dbName, persistConnection: false, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: false, autoOptimize: false); -#endif - } - /// /// Opens an inspection connection carrying the same key the database was created with. /// Tycho holds locking_mode = EXCLUSIVE and pooling keeps a disposed connection's lock diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 3a47080..a34739b 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -574,47 +574,6 @@ public static string EscapeSqlLiteral(string value) public static string DropIndex(string fullIndexName) => string.Concat(DropIndexPrefix, fullIndexName, ";"); - // Full ANALYZE: refreshes sqlite_stat1 so a newly created index is usable by the - // very next query. Every index is read in full: a sample (analysis_limit) of the - // type-ordered general index sees only the smallest types and makes the planner - // prefer it over the per-type partial index (see Tycho.RefreshStatistics). ANALYZE - // of the new index alone would mix a full row with whatever the others hold and - // can produce the same mis-ranking. - public const string Analyze = "PRAGMA analysis_limit = 0; ANALYZE;"; - - // PRAGMA user_version of a store whose statistics were gathered in full at least - // once. A store written by an earlier 5.x release reads 0 and may hold sampled - // rows, which look complete and current (nothing is missing and nothing has - // grown), so the first connect runs Analyze unconditionally. Written only when the - // stored value is lower, so a higher version is never lowered. The literal is the - // single source of both the stamp and the value compared against. - public const string FullStatisticsUserVersion = "1"; - - public const string UserVersion = "PRAGMA user_version;"; - - public const string StampFullStatistics = "PRAGMA user_version = " + FullStatisticsUserVersion + ";"; - - public const string HasStatTable = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1';"; - - // Whether JsonValue's statistics need gathering again: indexes without a - // sqlite_stat1 row, the row count recorded when statistics were gathered (the - // first number of the general index's row), and the exact row count now. SQLite's - // PRAGMA optimize makes this decision from the cell counts down the leftmost path - // of the table's b-tree, which a few large documents at the lowest rowids make an - // order of magnitude wrong, so it re-analyzed such stores on every call. The exact - // count is a scan of the covering general index: 36 ms on 1.8M rows. - public const string SelectStatisticsCoverage = - """ - SELECT - (SELECT count(*) FROM sqlite_master AS m - WHERE m.type = 'index' AND m.tbl_name = 'JsonValue' - AND NOT EXISTS (SELECT 1 FROM sqlite_stat1 AS s WHERE s.idx = m.name)), - (SELECT CAST(substr(stat, 1, instr(stat || ' ', ' ') - 1) AS INTEGER) - FROM sqlite_stat1 - WHERE tbl = 'JsonValue' AND idx = 'idx_jsonvalue_fulltypename_partition'), - (SELECT count(*) FROM JsonValue); - """; - public const string SelectIndexMetadata = """ SELECT PhysicalName, Definition, ShapeVersion diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 38ecd31..f4c87c2 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -36,9 +36,6 @@ private const string /// private const int IndexShapeVersion = 2; - private static readonly long FullStatisticsUserVersion = - long.Parse(Queries.FullStatisticsUserVersion, System.Globalization.CultureInfo.InvariantCulture); - // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); @@ -50,7 +47,6 @@ private const string private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; - private readonly bool _autoOptimize; // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -109,14 +105,11 @@ private const string /// Optional override for the SQLite page cache size, in KiB. Overrides the profile default. /// Optional override for the SQLite memory-map size, in bytes (0 disables mmap). Overrides the profile default. /// - /// Whether this instance maintains the store on its own: at connect it drops the - /// redundant indexes 4.x created and gathers planner statistics when the store has - /// none, they were sampled by an earlier release, or a table has grown tenfold, and - /// it refreshes statistics after CreateIndex. That work runs on the connecting - /// thread and can take 10–30 s on a large store upgraded from 4.x; pass false to - /// connect without it and call or - /// from a background thread at a convenient time, which does the same work. - /// Statistics are still refreshed when the connection closes. Default is true. + /// Whether connecting drops the redundant indexes 4.x created. Freeing their pages + /// runs on the connecting thread and took 10–30 s on a large store upgraded from + /// 4.x; pass false to connect without it and call or + /// from a background thread at a convenient time, which + /// does the same work. Default is true. /// public Tycho( string dbPath, @@ -168,7 +161,6 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; - _autoOptimize = autoOptimize; _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize); } @@ -286,7 +278,6 @@ public void Disconnect() { if (_connection is not null) { - RefreshStaleStatistics(_connection); _connection.Close(); _connection.Dispose(); _connection = null; @@ -305,134 +296,12 @@ public async ValueTask DisconnectAsync() return; } - RefreshStaleStatistics(_connection); - await _connection.CloseAsync().ConfigureAwait(false); await _connection.DisposeAsync().ConfigureAwait(false); _connection = null; } - /// - /// Re-analyzes when a connection closes if says - /// so, so expression indexes over JSON_EXTRACT keep being chosen by an app that - /// grew its data this session. The open-time counterpart is - /// . - /// - /// Statistics are always read from the whole of each index: the general - /// (FullTypeName, Partition) index is ordered by type name, so a sample of - /// its first few hundred entries sees only the smallest types and credits every - /// type with a handful of rows, while a sample of a per-type partial index sits - /// inside one key and credits every key with hundreds. The planner then prefers - /// the general index and reads every row of the type on each lookup. - /// - /// Best-effort: failures never block teardown. - /// - private static void RefreshStaleStatistics(SqliteConnection connection) - { - try - { - using var command = connection.CreateCommand(); - if (StatisticsNeedRefresh(command)) - { - AnalyzeAndStamp(command); - } - } - catch - { - // Advisory only — ignore failures during teardown. - } - } - - /// - /// Gathers planner statistics for a freshly opened connection, which covers a - /// mobile app that connects once and never cleanly disconnects. A store written by - /// an earlier release gets one full ANALYZE and the stamp, because the - /// sampled rows those releases wrote look complete and current; a store stamped - /// with is re-analyzed only when - /// says so. Best-effort: failures never block - /// connect. - /// - private static void RefreshStatistics(SqliteConnection connection) - { - try - { - GatherStatistics(connection); - } - catch - { - // Statistics are an optimization, not a correctness requirement. - } - } - - /// - /// The work of , letting failures propagate so that - /// reports them. - /// - private static void GatherStatistics(SqliteConnection connection) - { - using var command = connection.CreateCommand(); - - if (ReadUserVersion(command) >= FullStatisticsUserVersion && !StatisticsNeedRefresh(command)) - { - return; - } - - AnalyzeAndStamp(command); - } - - /// - /// True when an index of JsonValue has no sqlite_stat1 row, or the - /// exact row count differs tenfold from the count recorded when statistics were - /// gathered. SQLite's own PRAGMA optimize decides this from the cell counts - /// down the leftmost path of the table's b-tree, which a few large documents at - /// the lowest rowids make an order of magnitude wrong, so it re-analyzed such - /// stores on every call; the exact count is a scan of the covering general index. - /// - private static bool StatisticsNeedRefresh(SqliteCommand command) - { - command.CommandText = Queries.HasStatTable; - if (command.ExecuteScalar() is null) - { - return true; - } - - command.CommandText = Queries.SelectStatisticsCoverage; - using var reader = command.ExecuteReader(); - if (!reader.Read() || reader.GetInt64(0) > 0 || reader.IsDBNull(1)) - { - return true; - } - - long recordedRows = reader.GetInt64(1); - long rows = reader.GetInt64(2); - - if (recordedRows == 0) - { - return rows > 0; - } - - return rows >= recordedRows * 10 || rows <= recordedRows / 10; - } - - private static void AnalyzeAndStamp(SqliteCommand command) - { - command.CommandText = Queries.Analyze; - command.ExecuteNonQuery(); - - if (ReadUserVersion(command) < FullStatisticsUserVersion) - { - command.CommandText = Queries.StampFullStatistics; - command.ExecuteNonQuery(); - } - } - - private static long ReadUserVersion(SqliteCommand command) - { - command.CommandText = Queries.UserVersion; - return command.ExecuteScalar() is long version ? version : 0L; - } - public void Backup(SqliteConnection backupDatabaseConnection) { _connection?.BackupDatabase(backupDatabaseConnection); @@ -2343,10 +2212,10 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) /// /// Mobile apps typically call CreateIndex on every launch, so the already-current /// case must be cheap: it costs one metadata lookup and one sqlite_master probe, - /// with no DDL and no ANALYZE. + /// with no DDL. /// /// - private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition, bool analyze) + private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) { using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); @@ -2392,25 +2261,6 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de throw new TychoException($"Failed to Create Index: {definition.PhysicalName}", ex); } - // Refresh planner statistics outside the transaction so the index just - // created is usable by the very next query rather than only after a - // Disconnect. Advisory: a failure here must not fail index creation. An - // instance that opted out of automatic maintenance skips this; its new index - // gets statistics at Optimize or at the next Disconnect, whichever comes - // first, and until then the planner estimates it by default heuristics, - // which still favor it. - if (analyze) - { - try - { - ExecuteNonQuery(conn, Queries.Analyze); - } - catch - { - // Statistics are an optimization, not a correctness requirement. - } - } - return true; } @@ -2485,8 +2335,8 @@ private Tycho CreateIndexCore( _connection .WithConnectionBlock( _connectionGate, - (definition, analyze: _autoOptimize), - static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.analyze), + definition, + static (conn, definition) => ExecuteCreateIndex(conn, definition), _persistConnection); return this; @@ -2511,8 +2361,8 @@ private ValueTask CreateIndexCoreAsync( return _connection .WithConnectionBlockAsync( _connectionGate, - (definition, analyze: _autoOptimize), - static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.analyze), + definition, + static (conn, definition) => ExecuteCreateIndex(conn, definition), _persistConnection, cancellationToken); } @@ -2756,19 +2606,16 @@ public IReadOnlyList ListIndexes() } /// - /// Does the maintenance connecting does on its own when autoOptimize is on: - /// drops the redundant indexes earlier versions created, then gathers planner - /// statistics — a full ANALYZE on a store written by an earlier release, or - /// when an index has no statistics, or when the row count moved tenfold since they - /// were gathered; otherwise nothing. With nothing to do it costs an exact row count - /// (36 ms on 1.8M rows), so calling it on every launch is fine. + /// Does what connecting does on its own when autoOptimize is on: drops the + /// redundant indexes 4.x created. A no-op once they are gone, so calling it on + /// every launch is fine. /// /// Holds the database's single connection for the duration, so every other - /// operation on this instance waits: the first run on a 2.2 GB store upgraded from - /// 4.x took 17–24 s, and a re-analysis 3.2 s on a 1.68M-row store. The work runs on - /// the calling thread — Microsoft.Data.Sqlite executes synchronously, so - /// does not move it off the caller by itself — and must - /// not be called from a UI thread. + /// operation on this instance waits: freeing the indexes' pages took 10–30 s on a + /// large store upgraded from 4.x. The work runs on the calling thread — + /// Microsoft.Data.Sqlite executes synchronously, so + /// does not move it off the caller by itself — and must not be called from a UI + /// thread. /// /// public void Optimize() @@ -2805,7 +2652,6 @@ public ValueTask OptimizeAsync(CancellationToken cancellationToken = defau private static bool OptimizeStore(SqliteConnection conn) { ExecuteNonQuery(conn, Queries.DropLegacyIndexes); - GatherStatistics(conn); return true; } @@ -3069,11 +2915,6 @@ protected virtual void Dispose(bool disposing) if (disposing) { - if (_connection is not null) - { - RefreshStaleStatistics(_connection); - } - _connectionGate?.Dispose(); _connection?.Close(); _connection?.Dispose(); @@ -3137,8 +2978,8 @@ private SqliteConnection BuildConnection() connection .WithConnectionBlock( _connectionGate, - (script: _connectionScript, autoOptimize: _autoOptimize), - static (conn, state) => + _connectionScript, + static (conn, script) => { conn.Open(); @@ -3150,15 +2991,10 @@ private SqliteConnection BuildConnection() // Profile PRAGMAs + idempotent schema/index creation. Composed from // library constants and numeric profile values only (no user input). #pragma warning disable CA2100 - command.CommandText = state.script; + command.CommandText = script; #pragma warning restore CA2100 command.ExecuteNonQuery(); - - if (state.autoOptimize) - { - RefreshStatistics(conn); - } }, _persistConnection); @@ -3189,11 +3025,6 @@ private async ValueTask BuildConnectionAsync(CancellationToken command.ExecuteNonQuery(); - if (_autoOptimize) - { - RefreshStatistics(connection); - } - return connection; } finally From 8e8a0b9a86f99bc63320d1db19967869d0e037ed Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 10 Oct 2026 04:15:36 -0500 Subject: [PATCH 09/25] fix: remove the planner statistics earlier releases left behind A store written by 5.3.0 or 5.3.1 holds the sampled sqlite_stat1 rows that make the planner read every row of a type on each indexed lookup. The connect script now drops the statistics tables and reloads, so every connect, with or without autoOptimize, leaves the planner on its default heuristics. The reload (ANALYZE sqlite_master) leaves an empty sqlite_stat1 behind. --- TychoDB.UnitTests/IndexDdlTests.cs | 2 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 55 +++++++++++++++++++-- TychoDB/Queries.cs | 11 +++++ 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 4161025..f8354aa 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -229,7 +229,7 @@ public async Task CreateIndex_GathersNoPlannerStatistics() // see PlannerStatisticsTests for why statistics would only mislead it. using var conn = OpenInspection(Path.Combine(path, dbName)); using var command = conn.CreateCommand(); - command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name LIKE 'sqlite_stat%'"; + command.CommandText = "SELECT COUNT(*) FROM sqlite_stat1"; Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(0); } diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 809ffcf..9aa95c3 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -78,7 +78,7 @@ public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexChosen( (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - HasStatTable(dbFile).ShouldBeFalse(); + ReadStatRows(dbFile).ShouldBeEmpty(); AssertGroupLookupUsesPartialIndex(dbFile); } @@ -110,10 +110,31 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - HasStatTable(dbFile).ShouldBeFalse(); + ReadStatRows(dbFile).ShouldBeEmpty(); AssertGroupLookupUsesPartialIndex(dbFile); } + [TestMethod] + public async Task Connect_RemovesStatisticsLeftByAnEarlierRelease() + { + foreach (var autoOptimize in new[] { true, false }) + { + var dbFile = await SeedIndexedStore(); + var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + LeaveSampledStatistics(dbFile); + Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); + + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); + } + } + [TestMethod] public async Task WithoutStatistics_EqualityUsesThePartialIndex() { @@ -266,12 +287,27 @@ private static string ReadPhysicalIndexName(string dbFile, string indexName) return (string)command.ExecuteScalar(); } - private static bool HasStatTable(string dbFile) + /// Every statistics row in the store; connecting leaves sqlite_stat1 behind, empty. + private static List ReadStatRows(string dbFile) { + var rows = new List(); + using var conn = OpenInspection(dbFile); using var command = conn.CreateCommand(); - command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name LIKE 'sqlite_stat%'"; - return command.ExecuteScalar() is not null; + command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; + if (command.ExecuteScalar() is null) + { + return rows; + } + + command.CommandText = "SELECT tbl || ' ' || ifnull(idx, '-') || ' ' || stat FROM sqlite_stat1"; + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + rows.Add(reader.GetString(0)); + } + + return rows; } // ---------- seeding ---------- @@ -293,6 +329,15 @@ private static async Task SeedIndexedStore() return dbFile; } + /// Leaves what 5.3.1 left: statistics sampled at 400 rows per index. + private static void LeaveSampledStatistics(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE;"; + command.ExecuteNonQuery(); + } + private static List WideRows() { var rows = new List(WideRowCount); diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index a34739b..ce396cf 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -63,6 +63,17 @@ CREATE TABLE IF NOT EXISTS TychoIndex ShapeVersion INTEGER NOT NULL, PRIMARY KEY (IndexName, FullTypeName) ); + + -- The planner chooses the right index for every query TychoDB emits on its + -- default heuristics, and statistics only mislead it: a sample of the + -- type-ordered general index credits every type with a handful of rows, and + -- the planner then reads every row of a type on each indexed lookup. Earlier + -- releases gathered them. Whatever an ANALYZE left behind is dropped, and the + -- reload makes this connection forget what it read at open; it leaves an empty + -- sqlite_stat1 behind. + DROP TABLE IF EXISTS sqlite_stat1; + DROP TABLE IF EXISTS sqlite_stat4; + ANALYZE sqlite_master; """; // Indexes earlier versions created that duplicate either the primary-key autoindex From 322be818ebec4e812311ff7daf032f12a90858c5 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 10 Oct 2026 04:19:06 -0500 Subject: [PATCH 10/25] docs: describe why TychoDB gathers no planner statistics The write-up, CLI repro, README and CHANGELOG now describe the fix as shipped: no ANALYZE anywhere, leftovers dropped at connect, autoOptimize and Optimize covering only the legacy index drops. The repro script shows the plan for every query shape with no statistics; the row-estimate repro for PRAGMA optimize goes, since the pragma is no longer used. --- CHANGELOG.md | 51 ++--- README.md | 36 ++- docs/planner-statistics-row-estimate.sql | 76 ------- docs/planner-statistics-sampling.md | 276 ++++++++--------------- docs/planner-statistics-sampling.sql | 128 ++++------- 5 files changed, 180 insertions(+), 387 deletions(-) delete mode 100644 docs/planner-statistics-row-estimate.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 518b659..a0918b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,43 +14,28 @@ and credited every key with hundreds (`401`, against a true 542). The planner therefore preferred the general index over the partial one: 82–366 ms per lookup, 310 ms for a missing key, against 0–1 ms with full statistics or none at all. Results were identical - throughout; only speed changed. Statistics are no longer sampled: `CreateIndex` runs a - full `ANALYZE` (analyzing the new index alone would mix a full row with whatever the other - indexes hold and can mis-rank them the same way), and connect and disconnect run a full - `ANALYZE` when an index of `JsonValue` has no statistics or the table's exact row count - has moved tenfold since they were gathered — otherwise nothing. SQLite's own - `PRAGMA optimize` was tried first and rejected twice over: its default form caps the - analysis at 2,000 rows (plain `PRAGMA optimize`, even after `analysis_limit = 0`, wrote - `2001 501` against `101` and mis-ranked the indexes the same way), and its tenfold check - estimates the row count from the cell counts down the leftmost path of the table's - b-tree, which a few large documents at the lowest rowids make an order of magnitude - wrong: a 2.2 GB production store (1.84M rows, estimated at 174,370) was re-analyzed on - every call, 20–30 s each. The exact count is a scan of the covering general index, 36 ms - on 1.8M rows. A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on the 2.2 GB - store. A store written by an earlier 5.x release already holds sampled rows, which look - complete and current, so the first connect of such a store runs one full `ANALYZE` and - stamps it with `PRAGMA user_version = 1` (a higher value is never lowered). If an earlier - release writes to the store after that, its sampled rows return and are not detected. + throughout; only speed changed. TychoDB no longer gathers statistics at all: SQLite's + default heuristics choose the right index for every query shape it emits (equality, + range, sort with a limit, two indexed filters, an unindexed filter, a whole type, a + count — verified on both bundled engines), while keeping statistics correct would have + cost a full `ANALYZE` of 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, plus + a way to tell when they had gone stale. Connect drops the statistics tables an earlier + release left behind and reloads, so an upgraded store is repaired on its first connect + whether or not `autoOptimize` is on; an empty `sqlite_stat1` remains. ### Added - **`autoOptimize` constructor parameter (default `true`), `Optimize()` and - `OptimizeAsync()`.** Connecting a store written by an earlier version does one-time work - on the connecting thread: it drops the four redundant indexes 4.x created — most of a - 10–30 s first launch measured on a large upgraded store, since freeing an index's pages - takes time proportional to its size and SQLCipher's default `secure_delete` writes every - freed page back — and gathers planner statistics (3.2 s / 17.5 s above when they are - missing, sampled or stale). Pass `autoOptimize: false` to connect without either, and - without the `ANALYZE` after `CreateIndex` (a new index is chosen by default heuristics - until its statistics arrive); then call `Optimize()` or `OptimizeAsync()` when convenient - — on a loading page, for example. They do exactly the work connect skipped: the drops, - then a full `ANALYZE` on a store written by an earlier release, when an index has no - statistics, or when the row count moved tenfold — otherwise nothing, so a call with nothing - to do costs an exact row count (36 ms on 1.8M rows). They hold the single connection for the - duration, so every other operation on the instance waits (17–24 s on the 2.2 GB store), and - run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` - alone does not move the work off the caller — so call them from a background thread. The - disconnect-time check is unaffected by the opt-out. + `OptimizeAsync()`.** Connecting a store written by 4.x drops the four redundant indexes + it created — most of a 10–30 s first launch measured on a large upgraded store, since + freeing an index's pages takes time proportional to its size and SQLCipher's default + `secure_delete` writes every freed page back. Pass `autoOptimize: false` to connect + without the drops and call `Optimize()` or `OptimizeAsync()` when convenient — on a + loading page, for example; they are a no-op once the indexes are gone. They hold the + single connection for the duration, so every other operation on the instance waits, and + run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so + `OptimizeAsync` alone does not move the work off the caller — so call them from a + background thread. ## 5.3.1 — 2026-10-05 diff --git a/README.md b/README.md index eb8fe58..07bb264 100644 --- a/README.md +++ b/README.md @@ -496,18 +496,16 @@ This matters for how they behave: no DDL. Declaring the same index name with a *different* property rebuilds it and drops the old one, and indexes created by older versions are migrated away automatically. Declaring your indexes on every app launch is the intended usage. -- **Statistics are refreshed** with a full `ANALYZE` after an index is created, so a - new index is usable by the very next query, and connect and disconnect re-analyze - when an index has no statistics or the row count has moved tenfold since they were - gathered. - A store written by 5.3.1 or earlier gets one full `ANALYZE` on its first connect, to - replace the sampled statistics those versions wrote. Statistics are never sampled: a - sample of the type-ordered general index sees only the smallest types and would make - the planner prefer it over a partial index. Together with dropping the redundant - indexes 4.x created, that connect-time work can stall the first launch of a large - upgraded store for 10–30 s; pass `autoOptimize: false` to skip it (and the `ANALYZE` - after `CreateIndex`) and call `Optimize()` / `OptimizeAsync()` from a background thread - instead — the same work, ~0 ms when nothing changed. +- **No planner statistics.** TychoDB never runs `ANALYZE`. SQLite's default heuristics + choose the right index for every query shape TychoDB emits, and statistics only made + that choice worse: a sample of the type-ordered general index credits every type with + a handful of rows, and the planner then reads every row of the type on each indexed + lookup (5.3.0 and 5.3.1). Statistics an earlier release or an external `ANALYZE` left + in the file are removed at connect. +- **Dropping the indexes 4.x created** happens at connect and can stall the first launch + of a large upgraded store for 10–30 s; pass `autoOptimize: false` to skip it and call + `Optimize()` / `OptimizeAsync()` from a background thread instead — the same work, a + no-op once the indexes are gone. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). @@ -552,9 +550,9 @@ db.Disconnect(); // Or disconnect asynchronously await db.DisconnectAsync(); -// Open without the one-time upgrade work (dropping indexes left by earlier versions and -// gathering statistics can stall the first launch of a large store for 10–30 s) and run -// the same work later, from a background thread — on a loading page, for example +// Open without dropping the indexes 4.x created (freeing their pages can stall the first +// launch of a large upgraded store for 10–30 s) and do it later, from a background +// thread — on a loading page, for example var deferredDb = new Tycho(dbPath: "./data", jsonSerializer: serializer, autoOptimize: false); await deferredDb.ConnectAsync(); await Task.Run(() => deferredDb.Optimize()); @@ -611,10 +609,10 @@ await db.DeleteObjectsAsync(); // Optimize database performance and reduce size db.Cleanup(shrinkMemory: true, vacuum: true); -// Drop indexes left by earlier versions and bring planner statistics up to date; ~0 ms -// when nothing changed. Holds the connection for the duration — every other operation on -// this instance waits; 17–24 s on a 2.2 GB store upgraded from 4.x — and runs on the -// calling thread, so call it from a background thread, never the UI thread. +// Drop the indexes 4.x created; a no-op once they are gone. Holds the connection for the +// duration — every other operation on this instance waits; 10–30 s on a large store +// upgraded from 4.x — and runs on the calling thread, so call it from a background +// thread, never the UI thread. await Task.Run(() => db.Optimize()); ``` diff --git a/docs/planner-statistics-row-estimate.sql b/docs/planner-statistics-row-estimate.sql deleted file mode 100644 index 825c5ad..0000000 --- a/docs/planner-statistics-row-estimate.sql +++ /dev/null @@ -1,76 +0,0 @@ --- PRAGMA optimize decides whether a table needs re-analysis from an estimate of its row --- count: the product of the cell counts down the leftmost path of the table's b-tree. --- A few large documents at the lowest rowids leave the leftmost leaf nearly empty, the --- estimate lands an order of magnitude below the truth, and the pragma re-runs a full --- ANALYZE on every call although every index has a full, current statistics row. --- --- Usage: rm -f estimate.db estimate.db-wal estimate.db-shm; sqlite3 estimate.db < planner-statistics-row-estimate.sql --- Needs the sqlite3 CLI, 3.46 or later (older versions check growth only). Runs in about 3 s. --- --- Expected: [1] prints ANALYZE "main"."JsonValue" right after the full ANALYZE and the --- three timed optimize(0x10002) calls each take as long as the ANALYZE did; [2] shows the --- exact count the library uses instead, and the index it reads. - -.bail on -.mode list -.headers off - -PRAGMA journal_mode = WAL; -PRAGMA synchronous = OFF; - -CREATE TABLE JsonValue -( - Key TEXT NOT NULL, - FullTypeName TEXT NOT NULL, - Partition TEXT NOT NULL, - Data JSON NOT NULL, - PRIMARY KEY (Key, FullTypeName, Partition) -); -CREATE INDEX idx_jsonvalue_fulltypename_partition ON JsonValue (FullTypeName, Partition); - -.print -.print '== Seed: three ~3 KB documents first (the lowest rowids, one per leaf page), then' -.print ' 540,000 small rows of one type over 1,000 keys, and the partial index.' - -WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM s WHERE i < 2) -INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) -SELECT 'large-' || i, 'Aaa.LargeModel', '', json_object('Payload', replace(hex(zeroblob(1500)), '0', 'x')) -FROM s; - -WITH RECURSIVE s(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM s WHERE i < 539999) -INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) -SELECT 'wide-' || i, 'Zzz.Models.WideModel', '', json_object('GroupId', printf('G%04d', i % 1000), 'Seq', i) -FROM s; - -CREATE INDEX idx_GroupId_WideModel_0badcafe -ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) -WHERE FullTypeName = 'Zzz.Models.WideModel'; - --- --------------------------------------------------------------------------- -.print -.print '== [1] Full statistics, then what PRAGMA optimize thinks of them' -PRAGMA analysis_limit = 0; -.timer on -ANALYZE; -.timer off -SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; -SELECT 'real rows: ' || count(*) FROM JsonValue; -.print '-- optimize(0x10003) (debug) right after the full ANALYZE; nothing should be listed:' -PRAGMA optimize(0x10003); -.print '-- optimize(0x10002), three calls in a row:' -.timer on -PRAGMA optimize(0x10002); -PRAGMA optimize(0x10002); -PRAGMA optimize(0x10002); -.timer off - --- --------------------------------------------------------------------------- -.print -.print '== [2] The exact count the library compares with the recorded row count instead' -EXPLAIN QUERY PLAN SELECT count(*) FROM JsonValue; -.timer on -SELECT count(*) FROM JsonValue; -SELECT count(*) FROM JsonValue; -.timer off -SELECT 'recorded by ANALYZE: ' || CAST(substr(stat, 1, instr(stat || ' ', ' ') - 1) AS INTEGER) -FROM sqlite_stat1 WHERE tbl = 'JsonValue' AND idx = 'idx_jsonvalue_fulltypename_partition'; diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index dfc388d..87260f3 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -4,9 +4,9 @@ On a 1.68M-row store whose largest type held 586,986 rows, an equality lookup on an indexed property of that type took 82–366 ms, and a lookup for a missing key 310 ms. The same query -with correct statistics takes 0–1 ms. Results were identical in every case; only speed -changed. Stores upgraded from 4.4.2, whose indexes are the legacy non-partial shape, were -not affected. +with correct statistics, or with none, takes 0–1 ms. Results were identical in every case; +only speed changed. Stores upgraded from 4.4.2, whose indexes are the legacy non-partial +shape, were not affected. ## Why @@ -20,10 +20,10 @@ ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) WHERE FullTypeName = 'Zzz.Models.WideModel'; ``` -Two places gathered statistics with `PRAGMA analysis_limit = 400`: `Tycho.RunOptimize` -(`PRAGMA analysis_limit = 400; PRAGMA optimize;` on connect, disconnect and dispose) and -`Queries.AnalyzeBounded` (`PRAGMA analysis_limit = 400; ANALYZE;` after `CreateIndex`). -With a limit, `ANALYZE` reads only the first ~400 entries of each index: +5.3.0 started gathering planner statistics, and 5.3.1 gathered them with +`PRAGMA analysis_limit = 400` (`PRAGMA optimize` on connect, disconnect and dispose, and +`ANALYZE` after `CreateIndex`). With a limit, `ANALYZE` reads only the first ~400 entries of +each index: - The general index is ordered by type name, and the types that sort first are tiny (22, 112, 10, 202 rows… in the real store). Its sample spans a handful of types, so @@ -31,190 +31,112 @@ With a limit, `ANALYZE` reads only the first ~400 entries of each index: - The partial index is ordered by `(Partition, GroupId)`, so its sample sits inside one key and credits every key with ~401 rows. The truth is ~542 across 1,083 keys. -The planner compares 81 against 401 and chooses the general index, then reads and -JSON-parses every row of the type on each lookup. Full statistics (`586986 586986 542` -against `1682261 34332 31741`) or no statistics at all keep the partial index chosen. So -does a partial index with no statistics row next to a full, stale or zero-row general-index -row, and statistics taken on a few hundred rows before 540,000 arrive (probes on the -synthetic store); the only snapshots that mislead the planner are a sampled pair, a full -partial-index row next to a stale general-index row, or a partial-index row that says one -key holds the whole index. +The planner compares 81 against 401, chooses the general index, and reads and JSON-parses +every row of the type on each lookup. -Plain `PRAGMA optimize` cannot be used either: the default mask (`0xfffe`) includes bit -`0x10`, which applies a temporary 2,000-row limit regardless of `analysis_limit`. It wrote -`2001 501` against `101` and mis-ranked the indexes the same way. +## Fix + +TychoDB gathers no statistics, and removes any it finds. The connect script ends with +`DROP TABLE IF EXISTS sqlite_stat1; DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master;` +— the last statement is SQLite's documented way to reload statistics on an open connection, +and it leaves an empty `sqlite_stat1` behind. Nothing else runs `ANALYZE` or +`PRAGMA optimize`. The one-time index drops stay, behind `autoOptimize` and `Optimize`. -The bundled SQLite is 3.50.4 (`SQLitePCLRaw.bundle_e_sqlite3` 3.0.1) and 3.39.2 for the -Encrypted package (`bundle_e_sqlcipher` 2.1.10). Both are affected: the explicit `ANALYZE` -behaves identically, and the regression tests fail on both. +Without a `sqlite_stat1` row, SQLite's planner credits a partial index with half the table +and every index with a fixed selectivity per equality column, so the per-type partial index +beats the general index for the property it covers whatever the data looks like. Every +query shape TychoDB emits gets the right plan on the 544k-row synthetic store, on both +bundled engines (3.50.4 and SQLCipher's 3.39.2; the tests in +`TychoDB.UnitTests/PlannerStatisticsTests.cs` assert each one): + +| Query | Plan with no statistics | Time | +|---|---|---| +| equality on an indexed property | partial index | 0–1 ms | +| range on an indexed numeric property | partial index | 1 ms | +| sort on an indexed numeric property, `LIMIT 20` | partial index, no temp b-tree | 0 ms | +| two indexed equalities | one of the two partial indexes, chosen by rule | 0 ms | +| equality on an unindexed property | general index, then filter | 190 ms (reads the type; the only plan there is) | +| whole type | general index | 20 ms | +| count | general index, covering | 20 ms | + +The one thing statistics could add is the choice between two indexed properties filtered +together: without them the planner cannot tell which is more selective and picks one by +rule, so the lookup is bounded by the rows matching that property rather than the smaller +set. On the stores measured so far every indexed property is selective enough for this not +to matter. + +## Why not gather them properly instead + +The branch first did that: a full `ANALYZE` (`analysis_limit = 0`) after `CreateIndex` and +whenever an index had no statistics or a table had grown tenfold, a `user_version` stamp so +stores written by 5.3.1 were re-analyzed once, an opt-out so the connect-time cost could be +deferred, and finally TychoDB's own staleness check. Each layer existed to make gathering +statistics safe, and testing on real stores kept finding the next hole: + +- A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, on the + connecting thread. +- `PRAGMA optimize`, SQLite's recommended maintenance, cannot be used as is: its default + mask includes bit `0x10`, a temporary 2,000-row limit regardless of `analysis_limit`, so + it wrote `2001 501` against `101` and mis-ranked the indexes the same way (repro case 4). +- `PRAGMA optimize(0x10002)` lifts the limit but decides whether a table has grown from the + cell counts down the leftmost path of its b-tree. A 2.2 GB production store (1.84M rows, + estimated at 174,370) was re-analyzed on every call, 20–30 s each, because its lowest + rowids held large documents. Any store can drift into that layout. +- Statistics gathered on a few hundred rows, then 540,000 rows arriving, are fine; a full + partial-index row next to a stale general-index row is not; a 5.3.1 build writing to a + repaired store brings the sampled rows back undetected. The states that mislead the + planner are the inconsistent ones, and every refresh policy has a window in which the + store is inconsistent. + +With no statistics there is nothing to sample, go stale, half-refresh or roll back, and +plan choice stops depending on data layout or on which release last wrote the file. +`docs/indexing-analysis.md` (5.3.0) listed "planner statistics are never available" as a +defect to fix; the 5.3.0 speedups came from the partial-index redesign, not from the +statistics, and that finding is reversed. ## Repro - `docs/planner-statistics-sampling.sql` — sqlite3 CLI only, synthetic data, ~3 s. Forty - tiny types that sort first, one type with 540,000 rows over 1,000 keys, the same partial - index shape. Output on SQLite 3.51.0: - - | State | `sqlite_stat1` (partial / general) | Plan | Lookup | - |---|---|---|---| - | `analysis_limit = 400; ANALYZE` (stock 5.3.1) | `540000 401 401` / `543990 81 81` | general index | 196–217 ms, missing key 205 ms | - | `analysis_limit = 0; ANALYZE` | `540000 540000 540` / `543990 13269 13269` | partial index | 0–1 ms | - | no statistics | — | partial index | 0–1 ms | - | `PRAGMA optimize` (default mask), `analysis_limit = 0` | `540000 2001 501` / `543990 101 101` | general index | 220 ms | - | `PRAGMA optimize(0x10002)` | `540000 540000 540` / `543990 13269 13269` | partial index | 1 ms | - - Two more cases that shaped the fix: sampled rows already in the file are left alone by - `PRAGMA optimize(0x10002)` (nothing is missing, nothing grew), and a full row for the - partial index next to a sampled row for the general index still picks the general index. - -- `TychoDB.UnitTests/PlannerStatisticsTests.cs` — three tests through Tycho's own - `CreateIndexAsync`, `ConnectAsync` and dispose paths on a 20,400-row store (40 small - types, one type with 20,000 rows over 200 keys). Each asserts the plan for the library's - own filter SQL uses the partial index and that its statistics row reads from the whole - index (`20000 20000 100`). On 5.3.1 all three fail in both configurations with - `SEARCH JsonValue USING INDEX idx_jsonvalue_fulltypename_partition`. On the same - Tycho-written file, 5.3.1's statement leaves `20000 401 81` / `20400 10 10` and a lookup - takes 7–11 ms; the fixed build leaves `20000 20000 100` / `20400 498 498` and 0.03 ms. + tiny types that sort first, one type with 540,000 rows over 1,000 keys, the two partial + index shapes. Case 1 is 5.3.1's sampled statistics (general index, ~0.2 s per lookup); + case 2 is what TychoDB now does at connect (the table above); case 3 is a full `ANALYZE` + for comparison; case 4 is plain `PRAGMA optimize`. +- `TychoDB.UnitTests/PlannerStatisticsTests.cs` — through Tycho's own `CreateIndexAsync`, + `ConnectAsync` and dispose paths on a 20,400-row store (40 small types, one type with + 20,000 rows over 200 keys): the two scenarios that failed on 5.3.1 (index created after + the data, and data loaded after the index then reconnected), a store carrying 5.3.1's + sampled rows repaired on connect with `autoOptimize` on and off, and one test per query + shape in the table above. Each asserts the plan for the library's own SQL and that no + statistics row exists. Bound parameters are fine in the library: SQLite re-plans when a bound value touches a partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic plan. The tests bind the parameters; the CLI script uses literals. -## Fix - -- At connect and at disconnect/dispose, Tycho re-analyzes when an index of `JsonValue` has - no `sqlite_stat1` row or the exact `count(*)` differs tenfold from the row count recorded - in the general index's row, and otherwise does nothing. The branch first used SQLite's - `PRAGMA optimize(0x10002)` for this (the documented form for a long-lived connection at - open, without the default mask's 2,000-row cap, which reproduces the problem); the - follow-up below explains why it was replaced. -- After `CreateIndex`, `Queries.Analyze` runs `PRAGMA analysis_limit = 0; ANALYZE;`. It is - a full `ANALYZE`, not `ANALYZE `: a full row next to a sampled or stale row - for the general index still mis-ranks. It is an explicit `ANALYZE`, not `PRAGMA optimize`: - on 3.39.2 `optimize` only considers tables the planner has used on the connection, so it - would do nothing right after `CREATE INDEX`. -- A store written by an earlier 5.x release already holds sampled rows, which look complete - and current (repro case 6). On its first connect, Tycho runs one full `ANALYZE` and stamps - the store with `PRAGMA user_version = 1` (unused by Tycho until now); later connects use - the check above. -- `autoOptimize: false` connects without the one-time upgrade work — the four - `DROP INDEX IF EXISTS` for the indexes 4.x created (now `Queries.DropLegacyIndexes`, - appended to the connect script only when the option is on) and the statistics step above - — and skips the `ANALYZE` after `CreateIndex`; a new index without a statistics row is - chosen by default heuristics until its row arrives. `Optimize`/`OptimizeAsync` do exactly - what connect skipped: the drops, then the same conditional statistics step, so a call - with nothing to do costs ~0 ms and the app can run it on every launch. The drops stay: - they are what makes bulk writes 25–45% faster, and nothing else is removed. Disconnect - still runs `optimize(0x10002)` in both modes. -- README and CHANGELOG describe the new behavior. - ## Cost -| Store | Sampled `ANALYZE` | Full `ANALYZE` | -|---|---|---| -| synthetic, 544k rows (CLI) | 0.017 s | 0.13–0.26 s | -| real, 1.68M rows, fresh | 2.9 s | 3.2 s | -| real, 2.2 GB, upgraded from 4.4.2 | — | 17.5 s | - -The full `ANALYZE` runs after each new index, as before. Connect, disconnect and `Optimize` -run it only when an index has no statistics or the exact row count moved tenfold; otherwise -they cost the exact count, a scan of the covering general index (36 ms warm on 1.8M rows), -so the analysis is paid once per store, not per launch. - -## Decisions - -1. **Stores that already hold 5.3.1's sampled rows** are repaired once at connect: nothing - is missing and nothing grew, so `PRAGMA optimize(0x10002)` would leave them, and - re-declaring an unchanged index runs no `ANALYZE`; without the repair they would stay slow - until a table grew tenfold or an index changed. The repair costs one full `ANALYZE` per - existing store and is on by default. -2. **The connect-time work blocks the first launch of an upgraded store.** The `ANALYZE` - costs the 3.2 s / 17.5 s above the first time it runs on a store with no statistics (a - 4.x upgrade), one written by an earlier release, or one that grew tenfold. The four - legacy index drops were most of a 10–30 s stall MoveScoutPro measured on a large - upgraded store (main-thread samples in `sqlite3BtreeDropTable`/`clearDatabasePage`): - freeing an index's pages is proportional to its size, and with `secure_delete` on — - SQLCipher's default — every freed page is written back. On the 165 MB synthetic store, - dropping three ~15 MB legacy indexes took 6–7 ms each plain and 39–54 ms each with - `secure_delete`, in both auto-vacuum modes. Both stay on by default, with - `autoOptimize: false` as the opt-out and `Optimize`/`OptimizeAsync` for the app to run - them when convenient — before a large download for the drops (faster writes), after it - for the statistics (fresh plans), never during it. They hold the single connection for - the duration (17–24 s on the 2.2 GB store the first time, ~0 ms afterwards) and run on - the calling thread — Microsoft.Data.Sqlite executes synchronously, so the async form - alone does not move the work off the caller — so apps call them from a background - thread. The disconnect-time check is not affected by the opt-out. `CreateIndex` itself - drops a per-type legacy index and builds the partial one, which is the third piece of an - upgrade stall and already under the app's control through when it calls it. -3. **Review outcomes.** The opted-out `CreateIndex` no longer analyzes (an opted-out app - declaring N indexes would otherwise pay N full analyzes, ~2× each while the legacy - indexes survive); `user_version` is stamped only when lower, so a higher store version - is never clobbered; `OptimizeAsync` stays inline like every other async method, with the - threading caveat documented. Not changed: disconnect stays automatic (a mid-`ANALYZE` - kill rolls back and the next disconnect retries), and the opted-out connect skips the - statistics check entirely — when it is not a no-op it is the multi-second `ANALYZE` the - opt-out exists to avoid, and the launch-page `Optimize` covers it. -4. **Known limitation.** The stamp is never invalidated, so if a 5.3.1-or-earlier build - writes to the store after 5.3.2 has stamped it, its sampled rows return and nothing - detects them; `Optimize` sees a stamped store with nothing missing and nothing grown. - Downgrades are out of scope; a `force` flag on `Optimize` would be the remedy if it is - ever needed. - -## Follow-up: SQLite's tenfold check - -Testing the branch against four real device stores, MoveScoutPro found one (1.84M rows, -2.2 GB) on which `PRAGMA optimize(0x10002)` ran a full `ANALYZE` on every call — 2–30 s -each, at connect and disconnect by default and at every `Optimize()` otherwise — although -every index had a full, current statistics row. The pragma's tenfold check estimates the -table's row count from the cell counts down the leftmost path of its b-tree; on that store -the path was 265 × 329 × 2 = 174,370 against 1,841,652 rows, a ratio just past the -threshold, because the lowest rowids hold large documents and the leftmost leaf has two -cells. Reproduced synthetically (`docs/planner-statistics-row-estimate.sql`): a few ~3 KB -documents inserted before 540,000 small rows make `PRAGMA optimize(0x10003)` report -`ANALYZE "main"."JsonValue"` immediately after a full `ANALYZE`, and `optimize(0x10002)` -re-runs it on every call. Any store can drift into this layout as rows are rewritten. - -Tycho now decides staleness itself and no longer calls `PRAGMA optimize`: a stamped store -is re-analyzed only when an index of `JsonValue` has no `sqlite_stat1` row or the exact -`count(*)` differs tenfold from the row count recorded in the general index's row. The -count is a scan of the covering general index, 36 ms warm on 1.8M rows. This also removed -the probe read that SQLite 3.39.2 (the Encrypted package) had needed, since that build lets -`PRAGMA optimize` consider only tables the connection's planner has already used. The -regression test stores eight large documents first, plants a sentinel `sqlite_stat1` row -(a whole-database `ANALYZE` empties the table before rewriting it), connects twice, and -checks the sentinel survived; two more tests check that the analysis does run after a -tenfold growth or shrink and not after a sixfold one. One thing learned on the way: SQLite -reads a `sqlite_stat1` row whose index it does not know as that table's row count, so the -sentinel names `StreamValue`, not `JsonValue`. - -## Considered and not done - -Taking the choice away from the planner — a `+FullTypeName` term or `INDEXED BY` in the -generated SQL whenever a partial index applies — would make index choice independent of -statistics. It was not done: `+FullTypeName` would turn every filter on an unindexed -property into a scan of all types, SQLite documents `INDEXED BY` as a regression-testing -aid rather than a tuning tool, and the query builder would have to know which partial -indexes exist. The planner also does not need the help when statistics are consistent: a -partial index with no statistics row is chosen against a full, stale or sampled row for -the general index. The general index wins only when both rows were sampled, or when the -partial row is full and the general row stale — the inconsistent states, which the fix -removes by never sampling and never refreshing one index without the others. +Connect pays two `DROP TABLE IF EXISTS` (a schema lookup each when there is nothing to +drop) and a statistics reload (a pass over the indexes in the schema). A store written by +5.3.0 or 5.3.1 pays the drop of its small statistics table once. + +The four `DROP INDEX IF EXISTS` for the indexes 4.x created were most of a 10–30 s stall +MoveScoutPro measured on the first launch of a large upgraded store (main-thread samples in +`sqlite3BtreeDropTable`/`clearDatabasePage`): freeing an index's pages is proportional to +its size, and with `secure_delete` on — SQLCipher's default — every freed page is written +back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6–7 ms each +plain and 39–54 ms each with `secure_delete`. They stay on by default, because they make +bulk writes 25–45% faster; `autoOptimize: false` connects without them and +`Optimize`/`OptimizeAsync` run them later. Both hold the single connection for the +duration and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so +the async form alone does not move the work off the caller — so apps call them from a +background thread. `CreateIndex` itself drops a per-type legacy index and builds the +partial one, which is the other piece of an upgrade stall and already under the app's +control through when it calls it. ## Verification - Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and - Encrypted (3.39.2). -- New tests on 5.3.1: 3 failed in both configurations. With the fix: 3 passed in both. -- The change lands as four code commits, each building and passing the Debug suite on its - own: the core fix (3 tests, 365 passed); the first-connect repair of sampled stores and - the never-lowered `user_version` stamp (2 tests, 367); the `autoOptimize` opt-out with - `Optimize`/`OptimizeAsync` (5 tests, 372 — including one that observes, through a - non-persistent connection, that an opted-out `CreateIndex` leaves no statistics row and - the partial index is chosen anyway, and that `Optimize` then fills it in; and one in - `IndexDdlTests` showing the opt-out keeps the legacy indexes until `Optimize` drops - them); and the probe read that makes `PRAGMA optimize` consider `JsonValue` on SQLite - 3.39.2, which that observing test caught on the Encrypted build. -- Replacing `PRAGMA optimize` with Tycho's own staleness check added three tests (large - documents first; tenfold growth, with a sixfold growth as the negative; tenfold shrink) - and removed the need for the 3.39.2 probe. -- Final state: 375 passed, 4 skipped, 0 failed in both configurations (Debug 5 s, - Encrypted 1 m 36 s). + Encrypted (3.39.2). The two scenario tests fail on it in both configurations with + `SEARCH JsonValue USING INDEX idx_jsonvalue_fulltypename_partition`. +- Final state: 373 passed, 4 skipped, 0 failed in both configurations (Debug 3 s, + Encrypted 1 m 24 s). diff --git a/docs/planner-statistics-sampling.sql b/docs/planner-statistics-sampling.sql index 3506b7f..a409c22 100644 --- a/docs/planner-statistics-sampling.sql +++ b/docs/planner-statistics-sampling.sql @@ -1,14 +1,14 @@ -- Sampled ANALYZE (PRAGMA analysis_limit = 400) makes SQLite prefer the general --- (FullTypeName, Partition) index over a per-type partial expression index. +-- (FullTypeName, Partition) index over a per-type partial expression index; with no +-- statistics at all, every query shape TychoDB emits picks the right index. -- --- Usage: rm -f repro.db repro.db-wal repro.db-shm; sqlite3 repro.db < analyze-sampling-repro.sql --- Needs only the sqlite3 CLI (PRAGMA optimize(0x10002) needs 3.46+; written against 3.51.0). --- Every row is generated below; no application database is read. Runs in about 3 s. +-- Usage: rm -f repro.db repro.db-wal repro.db-shm; sqlite3 repro.db < planner-statistics-sampling.sql +-- Needs only the sqlite3 CLI (written against 3.51.0). Every row is generated below; no +-- application database is read. Runs in about 3 s. -- --- Expected: [1] and [4] choose idx_jsonvalue_fulltypename_partition and take ~0.2 s per --- lookup; [2], [3] and [5] choose the partial index and take ~0.001 s. [6] shows that --- optimize(0x10002) leaves already-sampled statistics alone; [7] that a full row for the --- partial index alone does not help while the general index's row is still sampled. +-- Expected: [1] chooses idx_jsonvalue_fulltypename_partition and takes ~0.2 s per lookup; +-- [2] chooses a partial index for every indexed shape and takes ~0.001 s; [3] matches [2] +-- at the price of the ANALYZE; [4] ends up sampled again. .bail on .mode list @@ -47,14 +47,17 @@ FROM s; SELECT 'first types in index order: ' || group_concat(FullTypeName || '=' || c, ', ') FROM (SELECT FullTypeName, count(*) AS c FROM JsonValue GROUP BY 1 ORDER BY 1 LIMIT 6); SELECT 'total rows: ' || count(*) FROM JsonValue; -SELECT 'wide rows: ' || count(*) || ', distinct GroupId: ' || count(DISTINCT JSON_EXTRACT(Data, '$.GroupId')) -FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel'; --- The shape TychoDB 5.x CreateIndex produces. +-- The shapes TychoDB 5.x CreateIndex produces: plain JSON_EXTRACT for a string property, +-- CAST(... as NUMERIC) for a numeric one. CREATE INDEX idx_GroupId_WideModel_0badcafe ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) WHERE FullTypeName = 'Zzz.Models.WideModel'; +CREATE INDEX idx_Seq_WideModel_0badcafe +ON JsonValue (Partition, CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC)) +WHERE FullTypeName = 'Zzz.Models.WideModel'; + -- --------------------------------------------------------------------------- .print .print '== [1] Sampled statistics, as 5.3.1 writes them: PRAGMA analysis_limit = 400; ANALYZE;' @@ -64,109 +67,70 @@ ANALYZE; .timer off SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; .print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'; .print '-- lookups (rows found | bytes read), then time:' .timer on SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0007'); SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0993'); SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'missing'); .timer off -- --------------------------------------------------------------------------- .print -.print '== [2] Full statistics: PRAGMA analysis_limit = 0; ANALYZE;' -.timer on -PRAGMA analysis_limit = 0; -ANALYZE; -.timer off -SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; -.print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); -.print '-- lookups:' -.timer on -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0007'); -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0993'); -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'missing'); -.timer off - --- --------------------------------------------------------------------------- -.print -.print '== [3] No statistics: DELETE FROM sqlite_stat1; ANALYZE sqlite_master;' -DELETE FROM sqlite_stat1; +.print '== [2] No statistics, as TychoDB connects: DROP TABLE sqlite_stat1; ANALYZE sqlite_master;' +DROP TABLE IF EXISTS sqlite_stat1; +DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master; SELECT 'stat1 rows: ' || count(*) FROM sqlite_stat1; -.print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +.print '-- equality on an indexed property:' +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'; +.print '-- range on an indexed numeric property:' +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC) > 539000; +.print '-- sort on an indexed numeric property with a limit (no temp b-tree):' +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' ORDER BY CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC) ASC LIMIT 20; +.print '-- two indexed equalities (one partial index, chosen by rule):' +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500' AND CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC) = 500; +.print '-- equality on an unindexed property (general index, then filter):' +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.Label') = 'row 7'; +.print '-- whole type, and count:' +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = ''; +EXPLAIN QUERY PLAN SELECT COUNT(*) FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = ''; .print '-- lookups:' .timer on SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0007'); SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0993'); SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'missing'); +SELECT count(*) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC) > 539000); +SELECT count(*) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' ORDER BY CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC) ASC LIMIT 20); +SELECT COUNT(*) FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = ''; .timer off -- --------------------------------------------------------------------------- .print -.print '== [4] Plain PRAGMA optimize from no statistics, even with analysis_limit = 0:' -.print ' the default mask (bit 0x10) caps the ANALYZE it runs at 2,000 rows per index.' -PRAGMA analysis_limit = 0; -PRAGMA optimize; -SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; -.print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); -.timer on -SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); -.timer off - --- --------------------------------------------------------------------------- -.print -.print '== [5] PRAGMA optimize(0x10002) from no statistics: full ANALYZE of every table.' -DELETE FROM sqlite_stat1; -ANALYZE sqlite_master; -.print '-- what it would run (0x10003 = same mask plus the debug bit):' -PRAGMA optimize(0x10003); +.print '== [3] Full statistics, for comparison: PRAGMA analysis_limit = 0; ANALYZE;' .timer on -PRAGMA optimize(0x10002); +PRAGMA analysis_limit = 0; +ANALYZE; .timer off SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; .print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'; .timer on SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); .timer off -.print '-- a second optimize(0x10002) with statistics already present does nothing:' -PRAGMA optimize(0x10003); -.timer on -PRAGMA optimize(0x10002); -.timer off -- --------------------------------------------------------------------------- .print -.print '== [6] A store that already holds the sampled statistics 5.3.1 writes, then optimize(0x10002):' -.print ' nothing is missing and nothing grew, so the sampled rows stay.' -PRAGMA analysis_limit = 400; -ANALYZE; +.print '== [4] The maintenance SQLite recommends, PRAGMA optimize, from no statistics:' +.print ' its default mask caps the ANALYZE it runs at 2,000 rows per index, so the' +.print ' statistics are sampled again, even after analysis_limit = 0.' +DROP TABLE IF EXISTS sqlite_stat1; +ANALYZE sqlite_master; PRAGMA analysis_limit = 0; -.print '-- what it would run:' -PRAGMA optimize(0x10003); -PRAGMA optimize(0x10002); +PRAGMA optimize; SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; .print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); - --- --------------------------------------------------------------------------- -.print -.print '== [7] Mixed: sampled row for the general index, full row for the partial index only.' -DELETE FROM sqlite_stat1; -ANALYZE sqlite_master; -PRAGMA analysis_limit = 400; -ANALYZE idx_jsonvalue_fulltypename_partition; -PRAGMA analysis_limit = 0; +EXPLAIN QUERY PLAN SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'; .timer on -ANALYZE idx_GroupId_WideModel_0badcafe; +SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); .timer off -SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; -.print '-- plan:' -EXPLAIN QUERY PLAN SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE FullTypeName = 'Zzz.Models.WideModel' AND Partition = '' AND JSON_EXTRACT(Data, '$.GroupId') = 'G0500'); From 120fc5c40e50f22a83aff375d2c3e59187b3bc58 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:53:08 -0500 Subject: [PATCH 11/25] fix: gather full planner statistics at index creation and pin the general index row Removing statistics altogether fixed the sampled-statistics regression but left the planner unable to rank two partial indexes on one type: with a filter on both properties it took whichever index was created last, 4.6 ms (57 ms on SQLCipher) against 0.02 ms for a one-row result at 40,000 rows. Statistics are now gathered in full, for JsonValue only, when CreateIndex builds an index or re-declares one that was built on an empty type and has rows now. Rows recorded for an empty type are not kept. The general index's sqlite_stat1 row is pinned to "N N/2 N/2": the per-type average ANALYZE writes there misleads the planner whenever one type dominates a store, into a table scan for every type when few types existed at ANALYZE time and into the general index over a big type's partial index otherwise. Half the table keeps the general index cheaper than a scan and dearer than any partial index whose match is under half the rows, so the partial indexes' accurate rows rank against each other. Upgraded stores are repaired once, gated on PRAGMA user_version: with autoOptimize on, the first connect replaces sampled rows with full ones (or discards them when the store has no expression index) and stamps the store; a stamped store pays one header read at connect and writes nothing, so schema_version no longer changes on every connect. With autoOptimize off, Optimize()/OptimizeAsync() perform the repair. PRAGMA optimize stays removed. Tests cover every query shape on both engines, both index creation orders, the empty-type-then-bulk-load case, the repair with autoOptimize on and off, a store without indexes, a fresh store, and that a current store is not written at connect. A PlannerStatistics benchmark measures the three shapes whose speed depends on statistics through the public API across launches. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 77 +++-- Directory.build.props | 2 +- README.md | 37 +-- .../Benchmarks/PlannerStatistics.cs | 176 +++++++++++ TychoDB.UnitTests/IndexDdlTests.cs | 18 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 281 ++++++++++++++---- TychoDB/Queries.cs | 99 +++++- TychoDB/Tycho.cs | 224 +++++++++++--- docs/indexing-analysis.md | 4 + docs/planner-statistics-sampling.md | 201 ++++++++----- docs/planner-statistics-sampling.sql | 5 +- 11 files changed, 882 insertions(+), 242 deletions(-) create mode 100644 TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index a0918b0..1a9c81c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,27 +1,48 @@ # Changelog -## 5.3.2 (unreleased) +## 5.4.0 (unreleased) ### Fixed - **Indexed lookups on a large type read and parsed every row of the type, because - planner statistics were sampled.** The `PRAGMA optimize` run on connect and disconnect - and the `ANALYZE` run after `CreateIndex` set `analysis_limit = 400`, so SQLite read only - the first ~400 entries of each index. The general `(FullTypeName, Partition)` index is - ordered by type name, and the types that sort first are typically tiny, so its sample - credited every type with a handful of rows (`81` on a 1.68M-row store whose largest type - held 586,986 rows), while the sample of a per-type partial index sat inside a single key - and credited every key with hundreds (`401`, against a true 542). The planner therefore - preferred the general index over the partial one: 82–366 ms per lookup, 310 ms for a - missing key, against 0–1 ms with full statistics or none at all. Results were identical - throughout; only speed changed. TychoDB no longer gathers statistics at all: SQLite's - default heuristics choose the right index for every query shape it emits (equality, - range, sort with a limit, two indexed filters, an unindexed filter, a whole type, a - count — verified on both bundled engines), while keeping statistics correct would have - cost a full `ANALYZE` of 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, plus - a way to tell when they had gone stale. Connect drops the statistics tables an earlier - release left behind and reloads, so an upgraded store is repaired on its first connect - whether or not `autoOptimize` is on; an empty `sqlite_stat1` remains. + planner statistics were sampled.** Since 5.0.1 the `PRAGMA optimize` run on connect and + disconnect, and since 5.1.1 the `ANALYZE` run after `CreateIndex`, set + `analysis_limit = 400`, so SQLite read only the first ~400 entries of each index. The + general `(FullTypeName, Partition)` index is ordered by type name, and the types that + sort first are typically tiny, so its sample credited every type with a handful of rows + (`81` on a 1.68M-row production store whose largest type held 586,986 rows), while the + sample of a per-type partial index sat inside a single key and credited every key with + hundreds (`401`, against a true 542). The planner therefore preferred the general index + over the partial one: 82–366 ms per lookup on that store, 310 ms for a missing key, + against under a millisecond with correct statistics. Results were identical throughout; + only speed changed. + + Statistics are now gathered in full (`analysis_limit = 0`), for `JsonValue` only, and + only when `CreateIndex` builds an index or re-declares one that was built while its type + was empty and has rows now; nothing samples, and nothing runs `PRAGMA optimize`. After + each `ANALYZE` the general index's `sqlite_stat1` row is pinned to half the table: the + per-type average `ANALYZE` writes there misleads the planner whenever one type dominates + a store — into a table scan for every type when the statistics were taken while few + types existed, and into the general index over a big type's partial index otherwise — + while half the table keeps the general index cheaper than a scan and dearer than any + partial index whose match is under half the rows, so the partial indexes' own, accurate + rows decide between themselves. Without any statistics, two indexed filters ANDed used + whichever partial index was created last: 4.6 ms (57 ms on SQLCipher) against 0.02 ms + for a one-row result at 40,000 rows when the less selective index came second. Rows + recorded for an empty type (`0 0 0`) are not kept. Verified plan-by-plan on both bundled + engines for every shape TychoDB emits: equality, a non-selective equality, range, sort + with a limit, two indexed filters in either creation order, an unindexed filter, a whole + type (large and tiny), and a count. + + An upgraded store is repaired once: when `autoOptimize` is on, the first connect + replaces its sampled rows with full ones (or discards them when the store has no + expression index, since statistics only serve to rank one against another) and stamps + `PRAGMA user_version`; a stamped store pays one header read at connect and writes + nothing — `schema_version` is unchanged across reconnects. With `autoOptimize: false` + the store keeps the plans it had on the previous release until `Optimize()` / + `OptimizeAsync()` runs the same repair. A full `ANALYZE` is proportional to the store: + 3.2 s on the 1.68M-row production store and 17.5 s on a 2.2 GB one, paid once per store + and once per index build. (#36) ### Added @@ -29,13 +50,14 @@ `OptimizeAsync()`.** Connecting a store written by 4.x drops the four redundant indexes it created — most of a 10–30 s first launch measured on a large upgraded store, since freeing an index's pages takes time proportional to its size and SQLCipher's default - `secure_delete` writes every freed page back. Pass `autoOptimize: false` to connect - without the drops and call `Optimize()` or `OptimizeAsync()` when convenient — on a - loading page, for example; they are a no-op once the indexes are gone. They hold the - single connection for the duration, so every other operation on the instance waits, and - run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so - `OptimizeAsync` alone does not move the work off the caller — so call them from a - background thread. + `secure_delete` writes every freed page back — and connecting a store written by + 5.0.1–5.3.1 repairs its statistics (above). Pass `autoOptimize: false` to connect without + either and call `Optimize()` or `OptimizeAsync()` when convenient — on a loading page, for + example; both are a no-op once the store is current. They hold the single connection for + the duration, so every other operation on the instance waits, and run on the calling + thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not + move the work off the caller — so call them from a background thread. The new constructor + parameter is source-compatible; assemblies that construct `Tycho` need recompiling. (#36) ## 5.3.1 — 2026-10-05 @@ -229,7 +251,9 @@ query plans: [docs/indexing-analysis.md](docs/indexing-analysis.md). shared one index name and the second `CREATE INDEX IF NOT EXISTS` silently did nothing. - **Planner statistics.** A bounded `ANALYZE` runs after an index is created, and `PRAGMA optimize` now also runs on connect. Previously `sqlite_stat1` was never - created at all, so the planner always ran on default heuristics. + created at all, so the planner always ran on default heuristics. *Superseded in 5.4.0: + the bound sampled the indexes and misled the planner; statistics are now gathered in + full at index creation and `PRAGMA optimize` no longer runs.* - **New API:** `DropIndex`, `DropIndexAsync`, and `ListIndexes()` (additive), plus `SortBuilder.OrderBy(SortDirection, string propertyPath, bool isPropertyPathNumeric)` so the raw-string sort overload can emit the numeric form its index is built on — @@ -259,6 +283,7 @@ index); batch writes **−44%**; database file with three indexes **20.2 → 8.4 (bounded by `analysis_limit = 400`) so the query planner keeps fresh statistics and continues to choose indexes — including expression indexes over `JSON_EXTRACT`. The connect-time call matters for long-lived mobile apps that never cleanly disconnect. + *Removed in 5.4.0; see its Fixed entry.* - **Bounded WAL on mobile.** The `Mobile` profile sets `journal_size_limit = 8 MB` so the WAL file truncates after a checkpoint instead of growing unbounded; `Desktop` leaves it unlimited. diff --git a/Directory.build.props b/Directory.build.props index dd97293..ec3172c 100644 --- a/Directory.build.props +++ b/Directory.build.props @@ -3,7 +3,7 @@ true latest $(NoWarn);CS1591 - 5.0.0 + 5.4.0 Eight-Bot, Inc. diff --git a/README.md b/README.md index 07bb264..7aef5c5 100644 --- a/README.md +++ b/README.md @@ -496,16 +496,19 @@ This matters for how they behave: no DDL. Declaring the same index name with a *different* property rebuilds it and drops the old one, and indexes created by older versions are migrated away automatically. Declaring your indexes on every app launch is the intended usage. -- **No planner statistics.** TychoDB never runs `ANALYZE`. SQLite's default heuristics - choose the right index for every query shape TychoDB emits, and statistics only made - that choice worse: a sample of the type-ordered general index credits every type with - a handful of rows, and the planner then reads every row of the type on each indexed - lookup (5.3.0 and 5.3.1). Statistics an earlier release or an external `ANALYZE` left - in the file are removed at connect. -- **Dropping the indexes 4.x created** happens at connect and can stall the first launch - of a large upgraded store for 10–30 s; pass `autoOptimize: false` to skip it and call - `Optimize()` / `OptimizeAsync()` from a background thread instead — the same work, a - no-op once the indexes are gone. +- **Statistics are gathered when an index is built**, in full, for the one table that + carries expression indexes, so the planner can rank a type's partial indexes against + each other from the very next query; re-declaring an index gathers them again only if + it was built while its type was empty and has rows now. Nothing samples and nothing runs + at connect on a current store. The general index's statistics row is pinned to half the + table, because the per-type average `ANALYZE` writes there misleads the planner whenever + one type dominates a store; 5.0.1–5.3.1 sampled the statistics instead, which made the + planner read every row of a large type on each indexed lookup. +- **Upgraded stores are repaired once at connect:** the redundant indexes 4.x created are + dropped (10–30 s on a large store), and the sampled statistics 5.0.1–5.3.1 left behind + are replaced (a full `ANALYZE`, proportional to the store's size). Pass + `autoOptimize: false` to skip both and call `Optimize()` / `OptimizeAsync()` from a + background thread instead — the same work, a no-op once the store is current. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). @@ -550,9 +553,9 @@ db.Disconnect(); // Or disconnect asynchronously await db.DisconnectAsync(); -// Open without dropping the indexes 4.x created (freeing their pages can stall the first -// launch of a large upgraded store for 10–30 s) and do it later, from a background -// thread — on a loading page, for example +// Open without the one-time upgrade maintenance (dropping the indexes 4.x created, 10–30 s +// on a large store; replacing the statistics 5.0.1–5.3.1 sampled, a full ANALYZE) and do +// it later, from a background thread — on a loading page, for example var deferredDb = new Tycho(dbPath: "./data", jsonSerializer: serializer, autoOptimize: false); await deferredDb.ConnectAsync(); await Task.Run(() => deferredDb.Optimize()); @@ -609,10 +612,10 @@ await db.DeleteObjectsAsync(); // Optimize database performance and reduce size db.Cleanup(shrinkMemory: true, vacuum: true); -// Drop the indexes 4.x created; a no-op once they are gone. Holds the connection for the -// duration — every other operation on this instance waits; 10–30 s on a large store -// upgraded from 4.x — and runs on the calling thread, so call it from a background -// thread, never the UI thread. +// Drop the indexes 4.x created and repair the statistics 5.0.1–5.3.1 sampled; a no-op +// once the store is current. Holds the connection for the duration — every other +// operation on this instance waits; 10–30 s on a large store upgraded from 4.x — and +// runs on the calling thread, so call it from a background thread, never the UI thread. await Task.Run(() => db.Optimize()); ``` diff --git a/TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs b/TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs new file mode 100644 index 0000000..9a88fe1 --- /dev/null +++ b/TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using BenchmarkDotNet.Attributes; +using Microsoft.Data.Sqlite; + +namespace TychoDB.Benchmarks.Benchmarks; + +/// +/// The query shapes whose speed depends on planner statistics, measured through the +/// public API on the layout that exposed the 5.3.1 regression: forty tiny types whose +/// names sort first, then one wide type with 40,000 rows, indexed on a unique property +/// (Seq) and a 200-value property (GroupId). The store is built, closed and +/// reopened like an app across launches, so whatever each release leaves in +/// sqlite_stat1 at CreateIndex, connect and dispose is what the planner sees. +/// +/// controls which partial index was created last: with +/// no statistics the planner cannot rank two partial indexes and takes the most recent, +/// so the two-property filter is fast in one order and slow in the other. +/// +/// +[MemoryDiagnoser] +[SimpleJob(launchCount: 1, warmupCount: 1, invocationCount: 16)] +public class PlannerStatistics +{ + private const string DbName = "tycho_planner_statistics_bench.db"; + private const int SmallTypeCount = 40; + private const int RowsPerSmallType = 10; + private const int GroupCount = 200; + private const int RowsPerGroup = 200; + private const int WideRowCount = GroupCount * RowsPerGroup; + + [Params(false, true)] + public bool SelectiveIndexFirst { get; set; } + + private Tycho _db; + + public class WideModel + { + public string Key { get; set; } + + public string GroupId { get; set; } + + public int Seq { get; set; } + + public string Label { get; set; } + } + + public class SmallModel + { + public string Key { get; set; } + + public int Id { get; set; } + } + + [GlobalSetup] + public async Task Setup() + { + var path = Path.GetTempPath(); + var dbFile = Path.Combine(path, DbName); + var serializer = new NewtonsoftJsonSerializer(); + + // Launch 1: the wide type is written. + using (var db = await new Tycho(path, serializer, DbName, rebuildCache: true, requireTypeRegistration: false).ConnectAsync()) + { + var rows = new List(WideRowCount); + for (int i = 0; i < WideRowCount; i++) + { + rows.Add(new WideModel + { + Key = $"wide-{i}", + GroupId = "G" + (i % GroupCount).ToString("D4", System.Globalization.CultureInfo.InvariantCulture), + Seq = i, + Label = $"row {i}", + }); + } + + await db.WriteObjectsAsync(rows, x => x.Key).ConfigureAwait(false); + } + + SeedSmallTypes(dbFile); + + // Launch 2: the app declares its indexes. + SqliteConnection.ClearAllPools(); + using (var db = await new Tycho(path, serializer, DbName, rebuildCache: false, requireTypeRegistration: false).ConnectAsync()) + { + if (SelectiveIndexFirst) + { + await db.CreateIndexAsync(x => x.Seq, "seq_idx").ConfigureAwait(false); + await db.CreateIndexAsync(x => x.GroupId, "group_idx").ConfigureAwait(false); + } + else + { + await db.CreateIndexAsync(x => x.GroupId, "group_idx").ConfigureAwait(false); + await db.CreateIndexAsync(x => x.Seq, "seq_idx").ConfigureAwait(false); + } + } + + // Launch 3: the one measured. + SqliteConnection.ClearAllPools(); + _db = await new Tycho(path, serializer, DbName, rebuildCache: false, requireTypeRegistration: false).ConnectAsync(); + } + + [GlobalCleanup] + public void Cleanup() => _db?.Dispose(); + + /// Equality on an indexed 200-value property: 200 rows of 40,000. + [Benchmark] + public async Task IndexedEqualityAsync() + { + var filter = FilterBuilder.Create().Filter(FilterType.Equals, x => x.GroupId, "G0042"); + var results = await _db.ReadObjectsAsync(filter: filter).ConfigureAwait(false); + _ = results.Count(); + } + + /// Two indexed equalities ANDed, one unique and one 200-value: 1 row. + [Benchmark] + public async Task TwoIndexedEqualitiesAsync() + { + var filter = FilterBuilder.Create() + .Filter(FilterType.Equals, x => x.GroupId, "G0042") + .And() + .Filter(FilterType.Equals, x => x.Seq, 20042); + var results = await _db.ReadObjectsAsync(filter: filter).ConfigureAwait(false); + _ = results.Count(); + } + + /// Every row of a 10-row type in a store dominated by the wide type. + [Benchmark] + public async Task ReadSmallTypeAsync() + { + var results = await _db.ReadObjectsAsync().ConfigureAwait(false); + _ = results.Count(); + } + + /// + /// Forty tiny types whose names sort before the wide type's, written straight to the + /// table so the general index starts with them, as a real store's does. One of them + /// is , read back through the public API. + /// + private static void SeedSmallTypes(string dbFile) + { + SqliteConnection.ClearAllPools(); + + using var conn = new SqliteConnection($"Filename={dbFile}"); + conn.Open(); + using var transaction = conn.BeginTransaction(); + using var insert = conn.CreateCommand(); + insert.Transaction = transaction; + insert.CommandText = + "INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) " + + "VALUES ($key, $fullTypeName, '', json_object('Key', $key, 'Id', $id))"; + + var key = insert.Parameters.Add("$key", SqliteType.Text); + var id = insert.Parameters.Add("$id", SqliteType.Integer); + var fullTypeName = insert.Parameters.Add("$fullTypeName", SqliteType.Text); + + for (int t = 0; t < SmallTypeCount; t++) + { + fullTypeName.Value = t == 0 + ? typeof(SmallModel).FullName + : "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); + + for (int i = 0; i < RowsPerSmallType; i++) + { + key.Value = "small-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + id.Value = i; + insert.ExecuteNonQuery(); + } + } + + transaction.Commit(); + } +} diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index f8354aa..318acd5 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -215,7 +215,7 @@ public async Task CreateIndex_ChangedDefinition_RebuildsAndLeavesNoStaleIndex() } [TestMethod] - public async Task CreateIndex_GathersNoPlannerStatistics() + public async Task CreateIndex_GathersFullPlannerStatistics() { var (path, dbName) = NewDbPath(); @@ -225,12 +225,13 @@ public async Task CreateIndex_GathersNoPlannerStatistics() await db.CreateIndexAsync(x => x.LongProperty, "long_idx"); } - // The planner runs on default heuristics, which favor the partial indexes; - // see PlannerStatisticsTests for why statistics would only mislead it. + // Building an index gathers full statistics for JsonValue (no analysis_limit), + // so the new index carries the type's true row count and the planner can rank + // it against the type's other indexes; see PlannerStatisticsTests. using var conn = OpenInspection(Path.Combine(path, dbName)); using var command = conn.CreateCommand(); - command.CommandText = "SELECT COUNT(*) FROM sqlite_stat1"; - Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(0); + command.CommandText = "SELECT stat FROM sqlite_stat1 WHERE idx LIKE 'idx_long_idx_%'"; + ((string)command.ExecuteScalar()).ShouldStartWith("100 "); } [TestMethod] @@ -426,9 +427,10 @@ public async Task BuiltInIndexes_AreSlimmed_WithoutRegressingCoreQueries() // bare SCAN/SEARCH assertion cannot (on a small single-type table a scan is // genuinely the cheaper plan). // - // Both sides of the comparison have to run on the same full statistics, which - // Tycho never gathers, so gather them here; the redundant indexes below are - // then analyzed too, and the comparison is like for like. + // Both sides of the comparison have to run on the same full statistics, so + // gather them here for every index in the file (Tycho analyzes JsonValue when + // it builds an index, not the redundant indexes created below by hand), and the + // comparison is like for like. Analyze(dbFile); var planBefore = CorePlans(dbFile); diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 9aa95c3..3712952 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -12,17 +12,17 @@ namespace TychoDB.UnitTests; /// -/// Proves the planner chooses the right index for every query shape TychoDB emits with no -/// planner statistics at all, and that TychoDB gathers none. +/// Pins how TychoDB keeps the planner able to choose the right index: full statistics for +/// JsonValue gathered when an index is built (or re-declared after being built on an +/// empty type), a one-time repair of the sampled rows 5.0.1–5.3.1 left behind, and nothing +/// at all at connect once a store is current. /// -/// Without a sqlite_stat1 row the planner credits a partial index with half the -/// table and every index with a fixed selectivity per equality column, so a per-type -/// partial index always beats the general (FullTypeName, Partition) index for the -/// property it covers, whatever the data looks like. Statistics can only make that choice -/// worse: a sample of the type-ordered general index sees only the smallest types and -/// credits every type with a handful of rows, while a sample of the partial index sits -/// inside one key and credits every key with hundreds, and the planner then reads every -/// row of the type on each lookup (5.3.1). +/// Sampled statistics (analysis_limit = 400) mislead the planner: a sample of the +/// type-ordered general index credits every type with a handful of rows, while a sample of +/// a per-type partial index sits inside one key and credits every key with hundreds, so the +/// planner read every row of the type on each indexed lookup. No statistics are not enough +/// either: with two partial indexes on one type and a filter on both properties, the planner +/// cannot tell which is more selective and takes whichever was created last. /// /// [TestClass] @@ -40,8 +40,11 @@ public class PlannerStatisticsTests private const int RowsPerGroup = 100; private const int WideRowCount = GroupCount * RowsPerGroup; + private const int BucketCount = 8; + private const string GroupIndexName = "group_idx"; private const string SeqIndexName = "seq_idx"; + private const string BucketIndexName = "bucket_idx"; private const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; private const string LookupGroup = "G0042"; @@ -55,6 +58,8 @@ public class WideModel public int Seq { get; set; } + public int Bucket { get; set; } + public string Label { get; set; } } @@ -78,7 +83,7 @@ public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexChosen( (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - ReadStatRows(dbFile).ShouldBeEmpty(); + AssertFullStatistics(dbFile, GroupIndexName); AssertGroupLookupUsesPartialIndex(dbFile); } @@ -88,12 +93,15 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() var (path, dbName) = NewDbPath(); var dbFile = Path.Combine(path, dbName); - // Launch 1: the app declares its index before any data exists. + // Launch 1: the app declares its index before any data exists; statistics + // gathered on an empty type are not kept. using (var db = await BuildDb(path, dbName).ConnectAsync()) { await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); } + ReadStatRows(dbFile).ShouldBeEmpty(); + SeedSmallTypes(dbFile); // Launch 2: a sync loads the large type, then the app closes. @@ -102,7 +110,8 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() await db.WriteObjectsAsync(WideRows(), x => x.Key); } - // Launch 3: the index is re-declared (a no-op) and queried. + // Launch 3: the index is re-declared; it has rows now but no statistics, so + // they are gathered before the query runs. using (var db = await BuildDb2(path, dbName).ConnectAsync()) { await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); @@ -110,33 +119,136 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - ReadStatRows(dbFile).ShouldBeEmpty(); + AssertFullStatistics(dbFile, GroupIndexName); AssertGroupLookupUsesPartialIndex(dbFile); } [TestMethod] - public async Task Connect_RemovesStatisticsLeftByAnEarlierRelease() + public async Task Connect_RepairsSampledStatisticsLeftByAnEarlierRelease() { - foreach (var autoOptimize in new[] { true, false }) + var dbFile = await SeedIndexedStore(); + var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + LeaveSampledStatistics(dbFile); + Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) { - var dbFile = await SeedIndexedStore(); - var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } - LeaveSampledStatistics(dbFile); - Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); + ReadUserVersion(dbFile).ShouldBe(1); + AssertFullStatistics(dbFile, GroupIndexName); + AssertGroupLookupUsesPartialIndex(dbFile); + } - using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } + [TestMethod] + public async Task Connect_WithAutoOptimizeOff_LeavesStatisticsUntilOptimize() + { + var dbFile = await SeedIndexedStore(); + var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); - ReadStatRows(dbFile).ShouldBeEmpty(); - AssertGroupLookupUsesPartialIndex(dbFile); + LeaveSampledStatistics(dbFile); + var sampled = ReadStatRows(dbFile); + + // Connect leaves the store exactly as the previous release did. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } + + ReadUserVersion(dbFile).ShouldBe(0); + ReadStatRows(dbFile).ShouldBe(sampled); + Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); + + // Optimize does the repair instead, once. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + (await db.OptimizeAsync()).ShouldBeTrue(); + } + + ReadUserVersion(dbFile).ShouldBe(1); + AssertFullStatistics(dbFile, GroupIndexName); + AssertGroupLookupUsesPartialIndex(dbFile); } [TestMethod] - public async Task WithoutStatistics_EqualityUsesThePartialIndex() + public async Task Connect_OnStoreWithoutIndexes_DiscardsStatisticsAndStamps() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(WideRows(), x => x.Key); + } + + LeaveSampledStatistics(dbFile); + ReadStatRows(dbFile).ShouldNotBeEmpty(); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + // Nothing to rank, so nothing to keep: the rows are discarded rather than analyzed. + ReadStatRows(dbFile).ShouldBeEmpty(); + ReadUserVersion(dbFile).ShouldBe(1); + } + + [TestMethod] + public async Task FreshStore_IsStampedAndHasNoStatisticsTable() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (await BuildDb(path, dbName).ConnectAsync()) + { + } + + ReadUserVersion(dbFile).ShouldBe(1); + StatisticsTableExists(dbFile).ShouldBeFalse(); + } + + [TestMethod] + public async Task Connect_OnCurrentStore_WritesNothing() + { + var dbFile = await SeedIndexedStore(); + var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + var schemaVersion = ReadSchemaVersion(dbFile); + var statRows = ReadStatRows(dbFile); + + for (int i = 0; i < 3; i++) + { + using var db = await BuildDb2(path, dbName).ConnectAsync(); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); + await db.CreateIndexAsync(x => x.Seq, SeqIndexName); + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + ReadSchemaVersion(dbFile).ShouldBe(schemaVersion); + ReadStatRows(dbFile).ShouldBe(statRows); + ReadUserVersion(dbFile).ShouldBe(1); + } + + [TestMethod] + public async Task TwoIndexedEqualities_UseTheMoreSelectiveIndex_InEitherCreationOrder() + { + foreach (var selectiveFirst in new[] { true, false }) + { + var dbFile = await SeedIndexedStore(seqIndexFirst: selectiveFirst); + + // Seq is unique; GroupId has 100 rows per value. Without statistics the planner + // takes whichever partial index was created last. + var plan = Explain(dbFile, filter: GroupFilter().And().Filter(FilterType.Equals, x => x.Seq, 42)); + + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", Case.Sensitive, $"seqIndexFirst: {selectiveFirst}"); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); + } + } + + [TestMethod] + public async Task WithStatistics_EqualityUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); @@ -147,7 +259,7 @@ public async Task WithoutStatistics_EqualityUsesThePartialIndex() } [TestMethod] - public async Task WithoutStatistics_RangeUsesThePartialIndex() + public async Task WithStatistics_RangeUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); @@ -160,7 +272,7 @@ public async Task WithoutStatistics_RangeUsesThePartialIndex() } [TestMethod] - public async Task WithoutStatistics_SortWithLimitUsesThePartialIndex() + public async Task WithStatistics_SortWithLimitUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); @@ -175,46 +287,51 @@ public async Task WithoutStatistics_SortWithLimitUsesThePartialIndex() } [TestMethod] - public async Task WithoutStatistics_TwoIndexedEqualitiesUseOneOfThePartialIndexes() + public async Task WithStatistics_NonSelectiveIndexedEqualityUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); - var plan = Explain( - dbFile, - filter: GroupFilter().And().Filter(FilterType.Equals, x => x.Seq, 42)); + // One of eight values: 2,500 rows, an eighth of the table. The general index's + // pinned row says half, so the partial index still wins. + var plan = Explain(dbFile, filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Bucket, 3)); - var partialIndexes = new[] - { - $"USING INDEX {ReadPhysicalIndexName(dbFile, GroupIndexName)}", - $"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", - }; - - partialIndexes.Count(name => plan.Contains(name, StringComparison.Ordinal)).ShouldBe(1); + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, BucketIndexName)}", Case.Sensitive); plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } [TestMethod] - public async Task WithoutStatistics_UnindexedPropertyUsesTheGeneralIndex() + public async Task WithStatistics_UnindexedPropertyUsesTheGeneralIndex() { var dbFile = await SeedIndexedStore(); - var plan = Explain( - dbFile, - filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Label, "row 7")); + var filter = FilterBuilder.Create().Filter(FilterType.Equals, x => x.Label, "row 7"); - plan.ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + Explain(dbFile, filter: filter).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + Explain(dbFile, filter: filter, fullTypeName: SmallTypeName(0)).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); } [TestMethod] - public async Task WithoutStatistics_WholeTypeUsesTheGeneralIndex() + public async Task WithStatistics_WholeTypeUsesTheGeneralIndex() { var dbFile = await SeedIndexedStore(); + // The wide type is 98% of the table and the small type 0.05%; both are reached + // through the general index, never by a scan, whatever ANALYZE averaged. Explain(dbFile).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + Explain(dbFile, fullTypeName: SmallTypeName(0)).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + } + + [TestMethod] + public async Task Statistics_GeneralIndexRowIsPinnedToHalfTheTable() + { + var dbFile = await SeedIndexedStore(); + + // Statistics were gathered when the wide type was the whole table. + ReadStatRows(dbFile).ShouldContain($"JsonValue {GeneralIndexName} {WideRowCount} {WideRowCount / 2} {WideRowCount / 2}"); } [TestMethod] - public async Task WithoutStatistics_CountUsesTheGeneralIndexWithoutReadingRows() + public async Task WithStatistics_CountUsesTheGeneralIndexWithoutReadingRows() { var dbFile = await SeedIndexedStore(); @@ -230,6 +347,38 @@ private static void AssertGroupLookupUsesPartialIndex(string dbFile) plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } + /// The index has a full statistics row: the type's true row count, not a 400-row sample. + private static void AssertFullStatistics(string dbFile, string indexName) + { + var physicalName = ReadPhysicalIndexName(dbFile, indexName); + var row = ReadStatRows(dbFile).SingleOrDefault(r => r.StartsWith($"JsonValue {physicalName} ", StringComparison.Ordinal)); + + row.ShouldNotBeNull($"no statistics row for {physicalName}"); + row.ShouldStartWith($"JsonValue {physicalName} {WideRowCount} "); + } + + private static long ReadUserVersion(string dbFile) => ReadPragma(dbFile, "user_version"); + + private static long ReadSchemaVersion(string dbFile) => ReadPragma(dbFile, "schema_version"); + + private static long ReadPragma(string dbFile, string pragma) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); +#pragma warning disable CA2100 // Pragma name is a test constant. + command.CommandText = "PRAGMA " + pragma; +#pragma warning restore CA2100 + return (long)command.ExecuteScalar(); + } + + private static bool StatisticsTableExists(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; + return command.ExecuteScalar() is not null; + } + private static FilterBuilder GroupFilter() => FilterBuilder.Create().Filter(FilterType.Equals, x => x.GroupId, LookupGroup); @@ -239,7 +388,8 @@ private static string Explain( FilterBuilder filter = null, SortBuilder sort = null, int? top = null, - bool count = false) + bool count = false, + string fullTypeName = null) { var sb = new StringBuilder(count ? Queries.SelectCountFromJsonValueWithFullTypeName : Queries.SelectDataFromJsonValueWithFullTypeName); var parameters = new FilterParameters(); @@ -259,7 +409,7 @@ private static string Explain( command.CommandText = "EXPLAIN QUERY PLAN " + sb; #pragma warning restore CA2100 - command.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); + command.Parameters.AddWithValue("$fullTypeName", fullTypeName ?? typeof(WideModel).FullName); command.Parameters.AddWithValue("$partition", string.Empty); for (int i = 0; i < parameters.Count; i++) { @@ -287,7 +437,7 @@ private static string ReadPhysicalIndexName(string dbFile, string indexName) return (string)command.ExecuteScalar(); } - /// Every statistics row in the store; connecting leaves sqlite_stat1 behind, empty. + /// Every statistics row in the store, as "tbl idx stat". private static List ReadStatRows(string dbFile) { var rows = new List(); @@ -313,15 +463,26 @@ private static List ReadStatRows(string dbFile) // ---------- seeding ---------- /// A store with the wide type indexed on GroupId and Seq, and the small types ahead of it. - private static async Task SeedIndexedStore() + private static async Task SeedIndexedStore(bool seqIndexFirst = false) { var (path, dbName) = NewDbPath(); using (var db = await BuildDb(path, dbName).ConnectAsync()) { await db.WriteObjectsAsync(WideRows(), x => x.Key); - await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); - await db.CreateIndexAsync(x => x.Seq, SeqIndexName); + + if (seqIndexFirst) + { + await db.CreateIndexAsync(x => x.Seq, SeqIndexName); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); + } + else + { + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); + await db.CreateIndexAsync(x => x.Seq, SeqIndexName); + } + + await db.CreateIndexAsync(x => x.Bucket, BucketIndexName); } var dbFile = Path.Combine(path, dbName); @@ -329,12 +490,15 @@ private static async Task SeedIndexedStore() return dbFile; } - /// Leaves what 5.3.1 left: statistics sampled at 400 rows per index. + /// + /// Leaves what 5.3.1 left: statistics sampled at 400 rows per index, and no + /// user_version stamp. + /// private static void LeaveSampledStatistics(string dbFile) { using var conn = OpenInspection(dbFile); using var command = conn.CreateCommand(); - command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE;"; + command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE; PRAGMA user_version = 0;"; command.ExecuteNonQuery(); } @@ -343,7 +507,7 @@ private static List WideRows() var rows = new List(WideRowCount); for (int i = 0; i < WideRowCount; i++) { - rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i, Label = $"row {i}" }); + rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i, Bucket = i % BucketCount, Label = $"row {i}" }); } return rows; @@ -352,6 +516,9 @@ private static List WideRows() private static string GroupId(int i) => "G" + (i % GroupCount).ToString("D4", System.Globalization.CultureInfo.InvariantCulture); + private static string SmallTypeName(int t) + => "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); + private static void SeedSmallTypes(string dbFile) { using var conn = OpenInspection(dbFile); @@ -367,7 +534,7 @@ private static void SeedSmallTypes(string dbFile) for (int t = 0; t < SmallTypeCount; t++) { - fullTypeName.Value = "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); + fullTypeName.Value = SmallTypeName(t); for (int i = 0; i < RowsPerSmallType; i++) { key.Value = "small-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index ce396cf..5c47c0c 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -64,16 +64,6 @@ CREATE TABLE IF NOT EXISTS TychoIndex PRIMARY KEY (IndexName, FullTypeName) ); - -- The planner chooses the right index for every query TychoDB emits on its - -- default heuristics, and statistics only mislead it: a sample of the - -- type-ordered general index credits every type with a handful of rows, and - -- the planner then reads every row of a type on each indexed lookup. Earlier - -- releases gathered them. Whatever an ANALYZE left behind is dropped, and the - -- reload makes this connection forget what it read at open; it leaves an empty - -- sqlite_stat1 behind. - DROP TABLE IF EXISTS sqlite_stat1; - DROP TABLE IF EXISTS sqlite_stat4; - ANALYZE sqlite_master; """; // Indexes earlier versions created that duplicate either the primary-key autoindex @@ -585,6 +575,95 @@ public static string EscapeSqlLiteral(string value) public static string DropIndex(string fullIndexName) => string.Concat(DropIndexPrefix, fullIndexName, ";"); + // ---- Planner statistics ---- + // + // Statistics exist for one decision: ranking two per-type partial indexes against + // each other when a query filters on both of their properties. Without a + // sqlite_stat1 row for each, the planner cannot tell which is more selective and + // takes the one created last; with rows gathered by a *sampled* ANALYZE + // (analysis_limit > 0) it is actively misled, because a sample of the type-ordered + // general index credits every type with a handful of rows while a sample of a + // partial index sits inside one key and credits every key with hundreds, and the + // planner then reads every row of the type on each indexed lookup (5.0.1–5.3.1). + // So statistics are gathered in full, for the one table that carries expression + // indexes, and only when an index is built or found to have none; nothing samples, + // and nothing runs at connect once a store has been repaired. + + // Full statistics for JsonValue, then two corrections and a reload. analysis_limit = 0 + // lifts any limit a caller set on the connection; neither ANALYZE nor a write to + // sqlite_stat1 changes schema_version. + // + // 1. Rows gathered while a type (or the table) was empty read "0 0 0" and are + // removed: the planner does better on its defaults than on "no rows", and a + // missing row is what makes CreateIndex gather statistics again once the type + // has rows. + // 2. The general index's row is pinned to "N N/2 N/2". ANALYZE writes the average + // rows per FullTypeName, and that average is wrong for every type in a store + // where one type dominates: taken while few types existed it says a type is the + // whole table and the planner scans instead of seeking, taken over many it says a + // big type is small and the planner prefers the general index to that type's + // partial index (the mechanism of the sampled-statistics regression, in a milder + // form). N/2 keeps the general index cheaper than a scan for any type (a scan + // costs about 3N in the planner's model, an index visit between 1.1 and 3 per + // row) and more expensive than a partial index for any equality whose value + // repeats on fewer than half the rows, any one-sided range (estimated at a + // quarter of the index without stat4) and any sort with a limit, which leaves the + // partial indexes' own rows — the accurate ones — to rank against each other. + // SQLite documents writing sqlite_stat1 for this purpose + // (https://www.sqlite.org/lang_analyze.html). + public const string AnalyzeJsonValue = + """ + PRAGMA analysis_limit = 0; + ANALYZE JsonValue; + DELETE FROM sqlite_stat1 WHERE tbl = 'JsonValue' AND (stat = '0' OR stat LIKE '0 %'); + UPDATE sqlite_stat1 + SET stat = CAST(stat AS INTEGER) || ' ' || max(CAST(stat AS INTEGER) / 2, 1) || ' ' || max(CAST(stat AS INTEGER) / 2, 1) + WHERE tbl = 'JsonValue' AND idx = 'idx_jsonvalue_fulltypename_partition'; + ANALYZE sqlite_master; + """; + + // SQLite's documented way to make an open connection re-read sqlite_stat1 + // (https://www.sqlite.org/lang_analyze.html). + public const string ReloadStatistics = "ANALYZE sqlite_master;"; + + // Discards every statistics row (sampled rows from an earlier release, or a + // caller's own ANALYZE) and reloads. Used only when the store has no expression + // index, so there is nothing for statistics to rank. The rows are deleted rather + // than the table dropped: the reload would recreate it anyway, and a DELETE is not + // a schema change. + public const string DropStatistics = + """ + DELETE FROM sqlite_stat1; + DROP TABLE IF EXISTS sqlite_stat4; + ANALYZE sqlite_master; + """; + + public const string StatisticsTableExists = + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1';"; + + public const string CountIndexMetadata = "SELECT COUNT(*) FROM TychoIndex;"; + + // The stat1 row for one physical index: " ...". NULL + // when the index has never been analyzed, or was analyzed while its type was empty. + public const string SelectIndexStatistics = + "SELECT stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' AND idx = $physicalName;"; + + // Whether a type has any rows at all; one probe of the general index. + public const string TypeHasRows = + "SELECT 1 FROM JsonValue WHERE FullTypeName = $fullTypeName LIMIT 1;"; + + // PRAGMA user_version of a store whose statistics are known to be unsampled: either + // repaired once by this release or created by it. A store written by an earlier + // release reads 0 and may carry sampled rows, which the connect-time repair + // replaces or discards exactly once before stamping; a stamped store does nothing + // at connect. The literal is the single source of both the stamp and the value + // compared against. + public const string StatisticsUserVersion = "1"; + + public const string UserVersion = "PRAGMA user_version;"; + + public const string StampStatisticsUserVersion = "PRAGMA user_version = " + StatisticsUserVersion + ";"; + public const string SelectIndexMetadata = """ SELECT PhysicalName, Definition, ShapeVersion diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index f4c87c2..d1e831b 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -47,6 +47,7 @@ private const string private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; + private readonly bool _autoOptimize; // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -105,11 +106,16 @@ private const string /// Optional override for the SQLite page cache size, in KiB. Overrides the profile default. /// Optional override for the SQLite memory-map size, in bytes (0 disables mmap). Overrides the profile default. /// - /// Whether connecting drops the redundant indexes 4.x created. Freeing their pages - /// runs on the connecting thread and took 10–30 s on a large store upgraded from - /// 4.x; pass false to connect without it and call or - /// from a background thread at a convenient time, which - /// does the same work. Default is true. + /// Whether connecting performs one-time store maintenance on the connecting thread: + /// dropping the redundant indexes 4.x created, and replacing the sampled planner + /// statistics 5.0.1–5.3.1 left behind with full ones (or discarding them when the + /// store has no expression index). Both run once per store; a store that is already + /// current pays a single header read at connect. The index drops took 10–30 s on a + /// large store upgraded from 4.x, and a full ANALYZE is proportional to the + /// store's size, so pass false to connect without either and call + /// or from a background thread + /// at a convenient time; until then an upgraded store keeps the plans it had on the + /// previous release. Default is true. /// public Tycho( string dbPath, @@ -161,6 +167,7 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; + _autoOptimize = autoOptimize; _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize); } @@ -2211,59 +2218,166 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) /// from any previous shape or name for the same logical index. /// /// Mobile apps typically call CreateIndex on every launch, so the already-current - /// case must be cheap: it costs one metadata lookup and one sqlite_master probe, - /// with no DDL. + /// case must be cheap: it costs one metadata lookup, one sqlite_master probe and + /// one statistics lookup, with no DDL. Building an index, or re-declaring one that + /// was built while its type was empty and now has rows, gathers full planner + /// statistics for JsonValue so the index is ranked correctly against the type's + /// other indexes from the very next query; see . /// /// private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) { - using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); + bool gatherStatistics; - try + using (var transaction = conn.BeginTransaction(IsolationLevel.Serializable)) { - if (IsIndexCurrent(conn, definition)) + try { - transaction.Commit(); - return true; + if (IsIndexCurrent(conn, definition)) + { + gatherStatistics = IndexLacksStatistics(conn, definition); + transaction.Commit(); + } + else + { + // Drop the previously recorded physical index (shape or definition + // changed) and any pre-metadata index that used the legacy name, so an + // upgraded database does not keep maintaining a stale b-tree forever. + foreach (var stalePhysicalName in ReadRecordedPhysicalNames(conn, definition)) + { + ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); + } + + if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) + { + ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + } + + ExecuteNonQuery(conn, definition.CommandText); + + using (var upsert = conn.CreateCommand()) + { + upsert.CommandText = Queries.UpsertIndexMetadata; + upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); + upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); + upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); + upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definition.CommandText }); + upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = IndexShapeVersion }); + upsert.ExecuteNonQuery(); + } + + transaction.Commit(); + gatherStatistics = true; + } + } + catch (Exception ex) + { + transaction.Rollback(); + throw new TychoException($"Failed to Create Index: {definition.PhysicalName}", ex); } + } + + if (gatherStatistics) + { + // Outside the transaction, so the index is committed whatever happens here. + // Advisory: statistics are an optimization, not a correctness requirement. + try + { + ExecuteNonQuery(conn, Queries.AnalyzeJsonValue); + } + catch + { + // A read-only file or medium cannot take statistics; the index still works. + } + } + + return true; + } + + /// + /// True when a current index has no statistics row although its type has rows: it + /// was never analyzed, or it was built while the type was empty (that row is not + /// kept, see ) and the data arrived later. + /// Either leaves the planner unable to rank this index against the type's other + /// indexes. The probe for rows is scoped to the type, so this only ever applies to + /// the per-type partial indexes the expression overloads create. + /// + private static bool IndexLacksStatistics(SqliteConnection conn, IndexDefinition definition) + { + using var command = conn.CreateCommand(); + command.CommandText = Queries.StatisticsTableExists; + + if (command.ExecuteScalar() is not null) + { + command.CommandText = Queries.SelectIndexStatistics; + command.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); - // Drop the previously recorded physical index (shape or definition - // changed) and any pre-metadata index that used the legacy name, so an - // upgraded database does not keep maintaining a stale b-tree forever. - foreach (var stalePhysicalName in ReadRecordedPhysicalNames(conn, definition)) + if (command.ExecuteScalar() is not null) { - ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); + return false; } - if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) + command.Parameters.Clear(); + } + + command.CommandText = Queries.TypeHasRows; + command.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); + return command.ExecuteScalar() is not null; + } + + /// + /// One-time repair of the planner statistics an earlier release left in the store, + /// keyed on PRAGMA user_version so a current store pays one header read and + /// writes nothing. A store below may hold + /// rows sampled with analysis_limit = 400, which mislead the planner into the + /// general index (5.0.1–5.3.1): when the store has expression indexes they are + /// replaced by full statistics, otherwise they are discarded, since statistics only + /// serve to rank one expression index against another. The store is then stamped. + /// Best-effort: failures never block connect. + /// + private static void RepairStatistics(SqliteConnection conn) + { + try + { + using var command = conn.CreateCommand(); + command.CommandText = Queries.UserVersion; + long userVersion = command.ExecuteScalar() is long version ? version : 0L; + + if (userVersion >= StatisticsUserVersion) { - ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + return; } - ExecuteNonQuery(conn, definition.CommandText); + command.CommandText = Queries.CountIndexMetadata; + bool hasExpressionIndexes = command.ExecuteScalar() is long count && count > 0; - using (var upsert = conn.CreateCommand()) + if (hasExpressionIndexes) { - upsert.CommandText = Queries.UpsertIndexMetadata; - upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); - upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); - upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); - upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definition.CommandText }); - upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = IndexShapeVersion }); - upsert.ExecuteNonQuery(); + command.CommandText = Queries.AnalyzeJsonValue; + command.ExecuteNonQuery(); + } + else + { + command.CommandText = Queries.StatisticsTableExists; + if (command.ExecuteScalar() is not null) + { + command.CommandText = Queries.DropStatistics; + command.ExecuteNonQuery(); + } } - transaction.Commit(); + command.CommandText = Queries.StampStatisticsUserVersion; + command.ExecuteNonQuery(); } - catch (Exception ex) + catch { - transaction.Rollback(); - throw new TychoException($"Failed to Create Index: {definition.PhysicalName}", ex); + // Statistics are an optimization, not a correctness requirement. } - - return true; } + private static readonly long StatisticsUserVersion = + long.Parse(Queries.StatisticsUserVersion, System.Globalization.CultureInfo.InvariantCulture); + /// /// True when the recorded definition matches what would be created now and the /// physical index is still present in the schema. @@ -2607,15 +2721,17 @@ public IReadOnlyList ListIndexes() /// /// Does what connecting does on its own when autoOptimize is on: drops the - /// redundant indexes 4.x created. A no-op once they are gone, so calling it on - /// every launch is fine. + /// redundant indexes 4.x created and, once per store, replaces the sampled planner + /// statistics 5.0.1–5.3.1 left behind with full ones (or discards them when the store + /// has no expression index). A no-op once both are done, so calling it on every + /// launch is fine. /// /// Holds the database's single connection for the duration, so every other /// operation on this instance waits: freeing the indexes' pages took 10–30 s on a - /// large store upgraded from 4.x. The work runs on the calling thread — - /// Microsoft.Data.Sqlite executes synchronously, so - /// does not move it off the caller by itself — and must not be called from a UI - /// thread. + /// large store upgraded from 4.x, and a full ANALYZE reads every index of + /// JsonValue once. The work runs on the calling thread — Microsoft.Data.Sqlite + /// executes synchronously, so does not move it off the + /// caller by itself — and must not be called from a UI thread. /// /// public void Optimize() @@ -2652,6 +2768,7 @@ public ValueTask OptimizeAsync(CancellationToken cancellationToken = defau private static bool OptimizeStore(SqliteConnection conn) { ExecuteNonQuery(conn, Queries.DropLegacyIndexes); + RepairStatistics(conn); return true; } @@ -2978,23 +3095,29 @@ private SqliteConnection BuildConnection() connection .WithConnectionBlock( _connectionGate, - _connectionScript, - static (conn, script) => + (Script: _connectionScript, AutoOptimize: _autoOptimize), + static (conn, state) => { conn.Open(); // Verified once per process (see EnsureJsonSupport). EnsureJsonSupport(conn); - using var command = conn.CreateCommand(); - - // Profile PRAGMAs + idempotent schema/index creation. Composed from - // library constants and numeric profile values only (no user input). + using (var command = conn.CreateCommand()) + { + // Profile PRAGMAs + idempotent schema/index creation. Composed from + // library constants and numeric profile values only (no user input). #pragma warning disable CA2100 - command.CommandText = script; + command.CommandText = state.Script; #pragma warning restore CA2100 - command.ExecuteNonQuery(); + command.ExecuteNonQuery(); + } + + if (state.AutoOptimize) + { + RepairStatistics(conn); + } }, _persistConnection); @@ -3025,6 +3148,11 @@ private async ValueTask BuildConnectionAsync(CancellationToken command.ExecuteNonQuery(); + if (_autoOptimize) + { + RepairStatistics(connection); + } + return connection; } finally diff --git a/docs/indexing-analysis.md b/docs/indexing-analysis.md index deebbb7..1eaf83f 100644 --- a/docs/indexing-analysis.md +++ b/docs/indexing-analysis.md @@ -124,6 +124,10 @@ win; the query-plan sweep in that bucket must confirm no query regresses to a ta ## 5. Statistics +> **5.4.0:** the bounded `ANALYZE` and `PRAGMA optimize` this section led to sampled the +> indexes and misled the planner; see `docs/planner-statistics-sampling.md` for the +> regression and the design that replaced them. + `sqlite_stat1` does not exist even after a full connect→index-create→dispose cycle — `Disconnect`'s `PRAGMA optimize` produced no statistics table in the diagnose run. All plans above are chosen by default heuristics. Bucket 3 adds a bounded `ANALYZE` after diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index 87260f3..2d94b99 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -1,4 +1,4 @@ -# Sampled planner statistics made SQLite skip the partial indexes (5.3.1) +# Sampled planner statistics made SQLite skip the partial indexes (5.0.1–5.3.1) ## Symptom @@ -20,10 +20,9 @@ ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) WHERE FullTypeName = 'Zzz.Models.WideModel'; ``` -5.3.0 started gathering planner statistics, and 5.3.1 gathered them with -`PRAGMA analysis_limit = 400` (`PRAGMA optimize` on connect, disconnect and dispose, and -`ANALYZE` after `CreateIndex`). With a limit, `ANALYZE` reads only the first ~400 entries of -each index: +5.0.1 started running `PRAGMA optimize` on connect and disconnect, and 5.1.1 added an +`ANALYZE` after `CreateIndex`; both set `PRAGMA analysis_limit = 400`. With a limit, +`ANALYZE` reads only the first ~400 entries of each index: - The general index is ordered by type name, and the types that sort first are tiny (22, 112, 10, 202 rows… in the real store). Its sample spans a handful of types, so @@ -36,78 +35,134 @@ every row of the type on each lookup. ## Fix -TychoDB gathers no statistics, and removes any it finds. The connect script ends with -`DROP TABLE IF EXISTS sqlite_stat1; DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master;` -— the last statement is SQLite's documented way to reload statistics on an open connection, -and it leaves an empty `sqlite_stat1` behind. Nothing else runs `ANALYZE` or -`PRAGMA optimize`. The one-time index drops stay, behind `autoOptimize` and `Optimize`. - -Without a `sqlite_stat1` row, SQLite's planner credits a partial index with half the table -and every index with a fixed selectivity per equality column, so the per-type partial index -beats the general index for the property it covers whatever the data looks like. Every -query shape TychoDB emits gets the right plan on the 544k-row synthetic store, on both -bundled engines (3.50.4 and SQLCipher's 3.39.2; the tests in -`TychoDB.UnitTests/PlannerStatisticsTests.cs` assert each one): - -| Query | Plan with no statistics | Time | -|---|---|---| -| equality on an indexed property | partial index | 0–1 ms | -| range on an indexed numeric property | partial index | 1 ms | -| sort on an indexed numeric property, `LIMIT 20` | partial index, no temp b-tree | 0 ms | -| two indexed equalities | one of the two partial indexes, chosen by rule | 0 ms | -| equality on an unindexed property | general index, then filter | 190 ms (reads the type; the only plan there is) | -| whole type | general index | 20 ms | -| count | general index, covering | 20 ms | - -The one thing statistics could add is the choice between two indexed properties filtered -together: without them the planner cannot tell which is more selective and picks one by -rule, so the lookup is bounded by the rows matching that property rather than the smaller -set. On the stores measured so far every indexed property is selective enough for this not -to matter. - -## Why not gather them properly instead - -The branch first did that: a full `ANALYZE` (`analysis_limit = 0`) after `CreateIndex` and -whenever an index had no statistics or a table had grown tenfold, a `user_version` stamp so -stores written by 5.3.1 were re-analyzed once, an opt-out so the connect-time cost could be -deferred, and finally TychoDB's own staleness check. Each layer existed to make gathering -statistics safe, and testing on real stores kept finding the next hole: - -- A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, on the - connecting thread. -- `PRAGMA optimize`, SQLite's recommended maintenance, cannot be used as is: its default - mask includes bit `0x10`, a temporary 2,000-row limit regardless of `analysis_limit`, so - it wrote `2001 501` against `101` and mis-ranked the indexes the same way (repro case 4). -- `PRAGMA optimize(0x10002)` lifts the limit but decides whether a table has grown from the - cell counts down the leftmost path of its b-tree. A 2.2 GB production store (1.84M rows, - estimated at 174,370) was re-analyzed on every call, 20–30 s each, because its lowest - rowids held large documents. Any store can drift into that layout. -- Statistics gathered on a few hundred rows, then 540,000 rows arriving, are fine; a full - partial-index row next to a stale general-index row is not; a 5.3.1 build writing to a - repaired store brings the sampled rows back undetected. The states that mislead the - planner are the inconsistent ones, and every refresh policy has a window in which the - store is inconsistent. - -With no statistics there is nothing to sample, go stale, half-refresh or roll back, and -plan choice stops depending on data layout or on which release last wrote the file. -`docs/indexing-analysis.md` (5.3.0) listed "planner statistics are never available" as a -defect to fix; the 5.3.0 speedups came from the partial-index redesign, not from the -statistics, and that finding is reversed. +Statistics are kept, gathered in full, and owned by TychoDB. + +- **When.** `CreateIndex` runs `PRAGMA analysis_limit = 0; ANALYZE JsonValue;` after it + builds an index, and again when it re-declares an index that was built while its type + was empty and has rows now (a re-declared index that is current and has a statistics + row costs one metadata lookup, one `sqlite_master` probe and one `sqlite_stat1` lookup, + no DDL). Nothing else gathers statistics: `PRAGMA optimize` is gone from connect, + disconnect and dispose. +- **What.** `ANALYZE JsonValue` only — the one table with expression indexes. Rows + recorded for an empty type (`0 0 0`) are deleted, so the planner uses its defaults + until the type has rows and the index is re-declared. The general index's row is then + pinned to `N N/2 N/2` and the connection reloads with `ANALYZE sqlite_master`. +- **Why pin.** `ANALYZE` writes the general index's row as the *average* rows per + `FullTypeName`, and in a store where one type dominates that average is wrong for every + type: taken while few types existed it says a type is the whole table and the planner + scans instead of seeking (every read of a ten-row settings type scans the 586,986-row + type); taken over many types it says the big type is small, and the planner prefers the + general index to that type's partial index — the sampled-statistics regression again, + in a milder form. In the planner's model a scan costs about 3N and an index visit + between 1.1 and 3 per row, so N/2 keeps the general index cheaper than a scan for any + type; and it is dearer than a partial index for any equality whose value repeats on + fewer than half the rows, any one-sided range (estimated at a quarter of the index + without stat4) and any sort with a limit. That leaves the partial indexes' own rows, + which are accurate, to rank against each other — the one thing statistics are for. + SQLite documents writing `sqlite_stat1` for this purpose + (https://www.sqlite.org/lang_analyze.html, "Manual Control Of Query Plans"). +- **Upgraded stores.** `PRAGMA user_version` gates a one-time repair: a store below the + stamp may carry sampled rows, so when `autoOptimize` is on the first connect replaces + them (full `ANALYZE` if the store has expression indexes, otherwise it discards them — + statistics only rank one expression index against another) and stamps the store. A + stamped store pays one header read at connect and writes nothing; `schema_version` is + stable across reconnects. With `autoOptimize: false`, connect leaves the store as the + previous release did and `Optimize()` / `OptimizeAsync()` performs the repair. + +Plans on the 20,400-row test store (40 small types, one type with 20,000 rows over 200 +keys, indexed on `GroupId`, a unique `Seq` and an 8-value `Bucket`), asserted by +`TychoDB.UnitTests/PlannerStatisticsTests.cs` on both bundled engines (SQLite 3.50.3 and +SQLCipher's 3.39.2): + +| Query | Plan | +|---|---| +| equality on an indexed property (100 of 20,000) | partial index | +| equality on a non-selective indexed property (2,500 of 20,000) | partial index | +| range on an indexed numeric property | partial index | +| sort on an indexed numeric property, `LIMIT 20` | partial index, no temp b-tree | +| two indexed equalities, unique index created first **or** last | the unique index | +| equality on an unindexed property, wide type and small type | general index | +| whole type, wide (98% of the table) and small (0.05%) | general index | +| count | general index, covering | + +## Why not "no statistics" + +This branch tried both of the other designs before landing here. + +*No statistics at all* (the connect script dropped `sqlite_stat1`) gets every single-index +shape right on the planner's defaults, and removes every way statistics can go stale or +inconsistent. But with two partial indexes on one type and a filter on both properties +the planner has nothing to rank them by and takes whichever was created last: measured +through `ReadObjectsAsync` at 40,000 rows, 0.022 ms → 4.56 ms (plain) and 0.019 ms → +57.5 ms (SQLCipher, where every extra page is decrypted) for a one-row result when the +less selective index came second. Which order a store ends up in is whatever order the +app first declared its indexes, so the regression is silent and permanent. + +*Full statistics as `ANALYZE` writes them*, with `PRAGMA optimize` to keep them fresh, +was the branch's first design and ran into: + +- `PRAGMA optimize`'s default mask includes bit `0x10`, a temporary 2,000-row limit + regardless of `analysis_limit`, so it wrote `2001 501` against `101` and mis-ranked the + indexes the same way (repro case 4). +- `PRAGMA optimize(0x10002)` lifts the limit but decides whether a table has grown from + the cell counts down the leftmost path of its b-tree. A 2.2 GB production store (1.84M + rows, estimated at 174,370) was re-analyzed on every call, 20–30 s each, because its + lowest rowids held large documents. +- A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on the 2.2 GB store, on + the connecting thread. +- The general index's averaged row misled the planner in both directions, as described + under *Why pin*. + +The design above keeps the full `ANALYZE` but runs it only where its result is used (an +index was built) or deferrable (`Optimize`), never on a timer or at every connect, and +removes the one row that `ANALYZE` gets wrong. + +## Cost + +- Connect on a current store: one `PRAGMA user_version` read. No DDL, no write. +- `CreateIndex` of a current index with statistics: one extra `sqlite_stat1` lookup. +- `CreateIndex` that builds an index, or re-declares one built on an empty type that has + rows now: a full `ANALYZE JsonValue`, proportional to the store (0.115 s at 544k rows + in the CLI repro; 3.2 s / 17.5 s on the production stores above). +- First connect of a store written by 5.0.1–5.3.1 with `autoOptimize` on: the same full + `ANALYZE` once if it has expression indexes, otherwise a `DELETE` of its statistics + rows; then the stamp. + +The four `DROP INDEX IF EXISTS` for the indexes 4.x created were most of a 10–30 s stall +measured on the first launch of a large upgraded store (main-thread samples in +`sqlite3BtreeDropTable`/`clearDatabasePage`): freeing an index's pages is proportional to +its size, and with `secure_delete` on — SQLCipher's default — every freed page is written +back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6–7 ms each +plain and 39–54 ms each with `secure_delete`. They stay on by default, because they make +bulk writes 25–45% faster; `autoOptimize: false` connects without them and +`Optimize`/`OptimizeAsync` run them later. Both hold the single connection for the +duration and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so +the async form alone does not move the work off the caller — so apps call them from a +background thread. `CreateIndex` itself drops a per-type legacy index and builds the +partial one, which is the other piece of an upgrade stall and already under the app's +control through when it calls it. ## Repro - `docs/planner-statistics-sampling.sql` — sqlite3 CLI only, synthetic data, ~3 s. Forty tiny types that sort first, one type with 540,000 rows over 1,000 keys, the two partial index shapes. Case 1 is 5.3.1's sampled statistics (general index, ~0.2 s per lookup); - case 2 is what TychoDB now does at connect (the table above); case 3 is a full `ANALYZE` - for comparison; case 4 is plain `PRAGMA optimize`. + case 2 is no statistics; case 3 is a full `ANALYZE`, the rows TychoDB now gathers before + pinning the general index's row; case 4 is plain `PRAGMA optimize`. - `TychoDB.UnitTests/PlannerStatisticsTests.cs` — through Tycho's own `CreateIndexAsync`, - `ConnectAsync` and dispose paths on a 20,400-row store (40 small types, one type with - 20,000 rows over 200 keys): the two scenarios that failed on 5.3.1 (index created after - the data, and data loaded after the index then reconnected), a store carrying 5.3.1's - sampled rows repaired on connect with `autoOptimize` on and off, and one test per query - shape in the table above. Each asserts the plan for the library's own SQL and that no - statistics row exists. + `ConnectAsync`, `OptimizeAsync` and dispose paths on the 20,400-row store: the two + scenarios that failed on 5.3.1 (index created after the data; index created on an empty + type, data loaded, reconnected), a store carrying 5.3.1's sampled rows repaired at + connect and, with `autoOptimize: false`, left alone until `Optimize`, a store without + indexes whose rows are discarded, a fresh store, `schema_version` and the statistics + unchanged across reconnects of a current store, the pinned general-index row, and one + test per query shape in the table above, including both creation orders of the two + partial indexes. +- `TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs` — the same layout at 40,000 rows + through the public API across three "launches": an indexed equality (the 5.3.1 + regression), two indexed equalities with the unique index created first or last (the + no-statistics regression), and a whole-type read of a ten-row type (the averaged-row + scan). `dotnet run --project TychoDB.Benchmarks -c Release -- --filter '*PlannerStatistics*'`. Bound parameters are fine in the library: SQLite re-plans when a bound value touches a partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic @@ -135,8 +190,8 @@ control through when it calls it. ## Verification -- Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and +- Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.3) and Encrypted (3.39.2). The two scenario tests fail on it in both configurations with `SEARCH JsonValue USING INDEX idx_jsonvalue_fulltypename_partition`. -- Final state: 373 passed, 4 skipped, 0 failed in both configurations (Debug 3 s, - Encrypted 1 m 24 s). +- Final state: 379 passed, 4 skipped, 0 failed in both configurations. +- Benchmark before/after: see the pull request. diff --git a/docs/planner-statistics-sampling.sql b/docs/planner-statistics-sampling.sql index a409c22..b73d66d 100644 --- a/docs/planner-statistics-sampling.sql +++ b/docs/planner-statistics-sampling.sql @@ -1,6 +1,7 @@ -- Sampled ANALYZE (PRAGMA analysis_limit = 400) makes SQLite prefer the general -- (FullTypeName, Partition) index over a per-type partial expression index; with no --- statistics at all, every query shape TychoDB emits picks the right index. +-- statistics at all, every single-index query shape TychoDB emits picks the right index +-- (two indexed filters ANDed do not: see planner-statistics-sampling.md). -- -- Usage: rm -f repro.db repro.db-wal repro.db-shm; sqlite3 repro.db < planner-statistics-sampling.sql -- Needs only the sqlite3 CLI (written against 3.51.0). Every row is generated below; no @@ -77,7 +78,7 @@ SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE -- --------------------------------------------------------------------------- .print -.print '== [2] No statistics, as TychoDB connects: DROP TABLE sqlite_stat1; ANALYZE sqlite_master;' +.print '== [2] No statistics: DROP TABLE sqlite_stat1; ANALYZE sqlite_master;' DROP TABLE IF EXISTS sqlite_stat1; DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master; From c0946fcb9fc4b1044fc7aad494be732bf263aa8a Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Thu, 15 Oct 2026 00:18:48 -0500 Subject: [PATCH 12/25] Revert "fix: gather full planner statistics at index creation and pin the general index row" This reverts commit 120fc5c40e50f22a83aff375d2c3e59187b3bc58. --- CHANGELOG.md | 77 ++--- Directory.build.props | 2 +- README.md | 37 ++- .../Benchmarks/PlannerStatistics.cs | 176 ----------- TychoDB.UnitTests/IndexDdlTests.cs | 18 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 281 ++++-------------- TychoDB/Queries.cs | 99 +----- TychoDB/Tycho.cs | 224 +++----------- docs/indexing-analysis.md | 4 - docs/planner-statistics-sampling.md | 201 +++++-------- docs/planner-statistics-sampling.sql | 5 +- 11 files changed, 242 insertions(+), 882 deletions(-) delete mode 100644 TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a9c81c..a0918b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,48 +1,27 @@ # Changelog -## 5.4.0 (unreleased) +## 5.3.2 (unreleased) ### Fixed - **Indexed lookups on a large type read and parsed every row of the type, because - planner statistics were sampled.** Since 5.0.1 the `PRAGMA optimize` run on connect and - disconnect, and since 5.1.1 the `ANALYZE` run after `CreateIndex`, set - `analysis_limit = 400`, so SQLite read only the first ~400 entries of each index. The - general `(FullTypeName, Partition)` index is ordered by type name, and the types that - sort first are typically tiny, so its sample credited every type with a handful of rows - (`81` on a 1.68M-row production store whose largest type held 586,986 rows), while the - sample of a per-type partial index sat inside a single key and credited every key with - hundreds (`401`, against a true 542). The planner therefore preferred the general index - over the partial one: 82–366 ms per lookup on that store, 310 ms for a missing key, - against under a millisecond with correct statistics. Results were identical throughout; - only speed changed. - - Statistics are now gathered in full (`analysis_limit = 0`), for `JsonValue` only, and - only when `CreateIndex` builds an index or re-declares one that was built while its type - was empty and has rows now; nothing samples, and nothing runs `PRAGMA optimize`. After - each `ANALYZE` the general index's `sqlite_stat1` row is pinned to half the table: the - per-type average `ANALYZE` writes there misleads the planner whenever one type dominates - a store — into a table scan for every type when the statistics were taken while few - types existed, and into the general index over a big type's partial index otherwise — - while half the table keeps the general index cheaper than a scan and dearer than any - partial index whose match is under half the rows, so the partial indexes' own, accurate - rows decide between themselves. Without any statistics, two indexed filters ANDed used - whichever partial index was created last: 4.6 ms (57 ms on SQLCipher) against 0.02 ms - for a one-row result at 40,000 rows when the less selective index came second. Rows - recorded for an empty type (`0 0 0`) are not kept. Verified plan-by-plan on both bundled - engines for every shape TychoDB emits: equality, a non-selective equality, range, sort - with a limit, two indexed filters in either creation order, an unindexed filter, a whole - type (large and tiny), and a count. - - An upgraded store is repaired once: when `autoOptimize` is on, the first connect - replaces its sampled rows with full ones (or discards them when the store has no - expression index, since statistics only serve to rank one against another) and stamps - `PRAGMA user_version`; a stamped store pays one header read at connect and writes - nothing — `schema_version` is unchanged across reconnects. With `autoOptimize: false` - the store keeps the plans it had on the previous release until `Optimize()` / - `OptimizeAsync()` runs the same repair. A full `ANALYZE` is proportional to the store: - 3.2 s on the 1.68M-row production store and 17.5 s on a 2.2 GB one, paid once per store - and once per index build. (#36) + planner statistics were sampled.** The `PRAGMA optimize` run on connect and disconnect + and the `ANALYZE` run after `CreateIndex` set `analysis_limit = 400`, so SQLite read only + the first ~400 entries of each index. The general `(FullTypeName, Partition)` index is + ordered by type name, and the types that sort first are typically tiny, so its sample + credited every type with a handful of rows (`81` on a 1.68M-row store whose largest type + held 586,986 rows), while the sample of a per-type partial index sat inside a single key + and credited every key with hundreds (`401`, against a true 542). The planner therefore + preferred the general index over the partial one: 82–366 ms per lookup, 310 ms for a + missing key, against 0–1 ms with full statistics or none at all. Results were identical + throughout; only speed changed. TychoDB no longer gathers statistics at all: SQLite's + default heuristics choose the right index for every query shape it emits (equality, + range, sort with a limit, two indexed filters, an unindexed filter, a whole type, a + count — verified on both bundled engines), while keeping statistics correct would have + cost a full `ANALYZE` of 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, plus + a way to tell when they had gone stale. Connect drops the statistics tables an earlier + release left behind and reloads, so an upgraded store is repaired on its first connect + whether or not `autoOptimize` is on; an empty `sqlite_stat1` remains. ### Added @@ -50,14 +29,13 @@ `OptimizeAsync()`.** Connecting a store written by 4.x drops the four redundant indexes it created — most of a 10–30 s first launch measured on a large upgraded store, since freeing an index's pages takes time proportional to its size and SQLCipher's default - `secure_delete` writes every freed page back — and connecting a store written by - 5.0.1–5.3.1 repairs its statistics (above). Pass `autoOptimize: false` to connect without - either and call `Optimize()` or `OptimizeAsync()` when convenient — on a loading page, for - example; both are a no-op once the store is current. They hold the single connection for - the duration, so every other operation on the instance waits, and run on the calling - thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not - move the work off the caller — so call them from a background thread. The new constructor - parameter is source-compatible; assemblies that construct `Tycho` need recompiling. (#36) + `secure_delete` writes every freed page back. Pass `autoOptimize: false` to connect + without the drops and call `Optimize()` or `OptimizeAsync()` when convenient — on a + loading page, for example; they are a no-op once the indexes are gone. They hold the + single connection for the duration, so every other operation on the instance waits, and + run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so + `OptimizeAsync` alone does not move the work off the caller — so call them from a + background thread. ## 5.3.1 — 2026-10-05 @@ -251,9 +229,7 @@ query plans: [docs/indexing-analysis.md](docs/indexing-analysis.md). shared one index name and the second `CREATE INDEX IF NOT EXISTS` silently did nothing. - **Planner statistics.** A bounded `ANALYZE` runs after an index is created, and `PRAGMA optimize` now also runs on connect. Previously `sqlite_stat1` was never - created at all, so the planner always ran on default heuristics. *Superseded in 5.4.0: - the bound sampled the indexes and misled the planner; statistics are now gathered in - full at index creation and `PRAGMA optimize` no longer runs.* + created at all, so the planner always ran on default heuristics. - **New API:** `DropIndex`, `DropIndexAsync`, and `ListIndexes()` (additive), plus `SortBuilder.OrderBy(SortDirection, string propertyPath, bool isPropertyPathNumeric)` so the raw-string sort overload can emit the numeric form its index is built on — @@ -283,7 +259,6 @@ index); batch writes **−44%**; database file with three indexes **20.2 → 8.4 (bounded by `analysis_limit = 400`) so the query planner keeps fresh statistics and continues to choose indexes — including expression indexes over `JSON_EXTRACT`. The connect-time call matters for long-lived mobile apps that never cleanly disconnect. - *Removed in 5.4.0; see its Fixed entry.* - **Bounded WAL on mobile.** The `Mobile` profile sets `journal_size_limit = 8 MB` so the WAL file truncates after a checkpoint instead of growing unbounded; `Desktop` leaves it unlimited. diff --git a/Directory.build.props b/Directory.build.props index ec3172c..dd97293 100644 --- a/Directory.build.props +++ b/Directory.build.props @@ -3,7 +3,7 @@ true latest $(NoWarn);CS1591 - 5.4.0 + 5.0.0 Eight-Bot, Inc. diff --git a/README.md b/README.md index 7aef5c5..07bb264 100644 --- a/README.md +++ b/README.md @@ -496,19 +496,16 @@ This matters for how they behave: no DDL. Declaring the same index name with a *different* property rebuilds it and drops the old one, and indexes created by older versions are migrated away automatically. Declaring your indexes on every app launch is the intended usage. -- **Statistics are gathered when an index is built**, in full, for the one table that - carries expression indexes, so the planner can rank a type's partial indexes against - each other from the very next query; re-declaring an index gathers them again only if - it was built while its type was empty and has rows now. Nothing samples and nothing runs - at connect on a current store. The general index's statistics row is pinned to half the - table, because the per-type average `ANALYZE` writes there misleads the planner whenever - one type dominates a store; 5.0.1–5.3.1 sampled the statistics instead, which made the - planner read every row of a large type on each indexed lookup. -- **Upgraded stores are repaired once at connect:** the redundant indexes 4.x created are - dropped (10–30 s on a large store), and the sampled statistics 5.0.1–5.3.1 left behind - are replaced (a full `ANALYZE`, proportional to the store's size). Pass - `autoOptimize: false` to skip both and call `Optimize()` / `OptimizeAsync()` from a - background thread instead — the same work, a no-op once the store is current. +- **No planner statistics.** TychoDB never runs `ANALYZE`. SQLite's default heuristics + choose the right index for every query shape TychoDB emits, and statistics only made + that choice worse: a sample of the type-ordered general index credits every type with + a handful of rows, and the planner then reads every row of the type on each indexed + lookup (5.3.0 and 5.3.1). Statistics an earlier release or an external `ANALYZE` left + in the file are removed at connect. +- **Dropping the indexes 4.x created** happens at connect and can stall the first launch + of a large upgraded store for 10–30 s; pass `autoOptimize: false` to skip it and call + `Optimize()` / `OptimizeAsync()` from a background thread instead — the same work, a + no-op once the indexes are gone. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). @@ -553,9 +550,9 @@ db.Disconnect(); // Or disconnect asynchronously await db.DisconnectAsync(); -// Open without the one-time upgrade maintenance (dropping the indexes 4.x created, 10–30 s -// on a large store; replacing the statistics 5.0.1–5.3.1 sampled, a full ANALYZE) and do -// it later, from a background thread — on a loading page, for example +// Open without dropping the indexes 4.x created (freeing their pages can stall the first +// launch of a large upgraded store for 10–30 s) and do it later, from a background +// thread — on a loading page, for example var deferredDb = new Tycho(dbPath: "./data", jsonSerializer: serializer, autoOptimize: false); await deferredDb.ConnectAsync(); await Task.Run(() => deferredDb.Optimize()); @@ -612,10 +609,10 @@ await db.DeleteObjectsAsync(); // Optimize database performance and reduce size db.Cleanup(shrinkMemory: true, vacuum: true); -// Drop the indexes 4.x created and repair the statistics 5.0.1–5.3.1 sampled; a no-op -// once the store is current. Holds the connection for the duration — every other -// operation on this instance waits; 10–30 s on a large store upgraded from 4.x — and -// runs on the calling thread, so call it from a background thread, never the UI thread. +// Drop the indexes 4.x created; a no-op once they are gone. Holds the connection for the +// duration — every other operation on this instance waits; 10–30 s on a large store +// upgraded from 4.x — and runs on the calling thread, so call it from a background +// thread, never the UI thread. await Task.Run(() => db.Optimize()); ``` diff --git a/TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs b/TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs deleted file mode 100644 index 9a88fe1..0000000 --- a/TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using BenchmarkDotNet.Attributes; -using Microsoft.Data.Sqlite; - -namespace TychoDB.Benchmarks.Benchmarks; - -/// -/// The query shapes whose speed depends on planner statistics, measured through the -/// public API on the layout that exposed the 5.3.1 regression: forty tiny types whose -/// names sort first, then one wide type with 40,000 rows, indexed on a unique property -/// (Seq) and a 200-value property (GroupId). The store is built, closed and -/// reopened like an app across launches, so whatever each release leaves in -/// sqlite_stat1 at CreateIndex, connect and dispose is what the planner sees. -/// -/// controls which partial index was created last: with -/// no statistics the planner cannot rank two partial indexes and takes the most recent, -/// so the two-property filter is fast in one order and slow in the other. -/// -/// -[MemoryDiagnoser] -[SimpleJob(launchCount: 1, warmupCount: 1, invocationCount: 16)] -public class PlannerStatistics -{ - private const string DbName = "tycho_planner_statistics_bench.db"; - private const int SmallTypeCount = 40; - private const int RowsPerSmallType = 10; - private const int GroupCount = 200; - private const int RowsPerGroup = 200; - private const int WideRowCount = GroupCount * RowsPerGroup; - - [Params(false, true)] - public bool SelectiveIndexFirst { get; set; } - - private Tycho _db; - - public class WideModel - { - public string Key { get; set; } - - public string GroupId { get; set; } - - public int Seq { get; set; } - - public string Label { get; set; } - } - - public class SmallModel - { - public string Key { get; set; } - - public int Id { get; set; } - } - - [GlobalSetup] - public async Task Setup() - { - var path = Path.GetTempPath(); - var dbFile = Path.Combine(path, DbName); - var serializer = new NewtonsoftJsonSerializer(); - - // Launch 1: the wide type is written. - using (var db = await new Tycho(path, serializer, DbName, rebuildCache: true, requireTypeRegistration: false).ConnectAsync()) - { - var rows = new List(WideRowCount); - for (int i = 0; i < WideRowCount; i++) - { - rows.Add(new WideModel - { - Key = $"wide-{i}", - GroupId = "G" + (i % GroupCount).ToString("D4", System.Globalization.CultureInfo.InvariantCulture), - Seq = i, - Label = $"row {i}", - }); - } - - await db.WriteObjectsAsync(rows, x => x.Key).ConfigureAwait(false); - } - - SeedSmallTypes(dbFile); - - // Launch 2: the app declares its indexes. - SqliteConnection.ClearAllPools(); - using (var db = await new Tycho(path, serializer, DbName, rebuildCache: false, requireTypeRegistration: false).ConnectAsync()) - { - if (SelectiveIndexFirst) - { - await db.CreateIndexAsync(x => x.Seq, "seq_idx").ConfigureAwait(false); - await db.CreateIndexAsync(x => x.GroupId, "group_idx").ConfigureAwait(false); - } - else - { - await db.CreateIndexAsync(x => x.GroupId, "group_idx").ConfigureAwait(false); - await db.CreateIndexAsync(x => x.Seq, "seq_idx").ConfigureAwait(false); - } - } - - // Launch 3: the one measured. - SqliteConnection.ClearAllPools(); - _db = await new Tycho(path, serializer, DbName, rebuildCache: false, requireTypeRegistration: false).ConnectAsync(); - } - - [GlobalCleanup] - public void Cleanup() => _db?.Dispose(); - - /// Equality on an indexed 200-value property: 200 rows of 40,000. - [Benchmark] - public async Task IndexedEqualityAsync() - { - var filter = FilterBuilder.Create().Filter(FilterType.Equals, x => x.GroupId, "G0042"); - var results = await _db.ReadObjectsAsync(filter: filter).ConfigureAwait(false); - _ = results.Count(); - } - - /// Two indexed equalities ANDed, one unique and one 200-value: 1 row. - [Benchmark] - public async Task TwoIndexedEqualitiesAsync() - { - var filter = FilterBuilder.Create() - .Filter(FilterType.Equals, x => x.GroupId, "G0042") - .And() - .Filter(FilterType.Equals, x => x.Seq, 20042); - var results = await _db.ReadObjectsAsync(filter: filter).ConfigureAwait(false); - _ = results.Count(); - } - - /// Every row of a 10-row type in a store dominated by the wide type. - [Benchmark] - public async Task ReadSmallTypeAsync() - { - var results = await _db.ReadObjectsAsync().ConfigureAwait(false); - _ = results.Count(); - } - - /// - /// Forty tiny types whose names sort before the wide type's, written straight to the - /// table so the general index starts with them, as a real store's does. One of them - /// is , read back through the public API. - /// - private static void SeedSmallTypes(string dbFile) - { - SqliteConnection.ClearAllPools(); - - using var conn = new SqliteConnection($"Filename={dbFile}"); - conn.Open(); - using var transaction = conn.BeginTransaction(); - using var insert = conn.CreateCommand(); - insert.Transaction = transaction; - insert.CommandText = - "INSERT INTO JsonValue (Key, FullTypeName, Partition, Data) " + - "VALUES ($key, $fullTypeName, '', json_object('Key', $key, 'Id', $id))"; - - var key = insert.Parameters.Add("$key", SqliteType.Text); - var id = insert.Parameters.Add("$id", SqliteType.Integer); - var fullTypeName = insert.Parameters.Add("$fullTypeName", SqliteType.Text); - - for (int t = 0; t < SmallTypeCount; t++) - { - fullTypeName.Value = t == 0 - ? typeof(SmallModel).FullName - : "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); - - for (int i = 0; i < RowsPerSmallType; i++) - { - key.Value = "small-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); - id.Value = i; - insert.ExecuteNonQuery(); - } - } - - transaction.Commit(); - } -} diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 318acd5..f8354aa 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -215,7 +215,7 @@ public async Task CreateIndex_ChangedDefinition_RebuildsAndLeavesNoStaleIndex() } [TestMethod] - public async Task CreateIndex_GathersFullPlannerStatistics() + public async Task CreateIndex_GathersNoPlannerStatistics() { var (path, dbName) = NewDbPath(); @@ -225,13 +225,12 @@ public async Task CreateIndex_GathersFullPlannerStatistics() await db.CreateIndexAsync(x => x.LongProperty, "long_idx"); } - // Building an index gathers full statistics for JsonValue (no analysis_limit), - // so the new index carries the type's true row count and the planner can rank - // it against the type's other indexes; see PlannerStatisticsTests. + // The planner runs on default heuristics, which favor the partial indexes; + // see PlannerStatisticsTests for why statistics would only mislead it. using var conn = OpenInspection(Path.Combine(path, dbName)); using var command = conn.CreateCommand(); - command.CommandText = "SELECT stat FROM sqlite_stat1 WHERE idx LIKE 'idx_long_idx_%'"; - ((string)command.ExecuteScalar()).ShouldStartWith("100 "); + command.CommandText = "SELECT COUNT(*) FROM sqlite_stat1"; + Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(0); } [TestMethod] @@ -427,10 +426,9 @@ public async Task BuiltInIndexes_AreSlimmed_WithoutRegressingCoreQueries() // bare SCAN/SEARCH assertion cannot (on a small single-type table a scan is // genuinely the cheaper plan). // - // Both sides of the comparison have to run on the same full statistics, so - // gather them here for every index in the file (Tycho analyzes JsonValue when - // it builds an index, not the redundant indexes created below by hand), and the - // comparison is like for like. + // Both sides of the comparison have to run on the same full statistics, which + // Tycho never gathers, so gather them here; the redundant indexes below are + // then analyzed too, and the comparison is like for like. Analyze(dbFile); var planBefore = CorePlans(dbFile); diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 3712952..9aa95c3 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -12,17 +12,17 @@ namespace TychoDB.UnitTests; /// -/// Pins how TychoDB keeps the planner able to choose the right index: full statistics for -/// JsonValue gathered when an index is built (or re-declared after being built on an -/// empty type), a one-time repair of the sampled rows 5.0.1–5.3.1 left behind, and nothing -/// at all at connect once a store is current. +/// Proves the planner chooses the right index for every query shape TychoDB emits with no +/// planner statistics at all, and that TychoDB gathers none. /// -/// Sampled statistics (analysis_limit = 400) mislead the planner: a sample of the -/// type-ordered general index credits every type with a handful of rows, while a sample of -/// a per-type partial index sits inside one key and credits every key with hundreds, so the -/// planner read every row of the type on each indexed lookup. No statistics are not enough -/// either: with two partial indexes on one type and a filter on both properties, the planner -/// cannot tell which is more selective and takes whichever was created last. +/// Without a sqlite_stat1 row the planner credits a partial index with half the +/// table and every index with a fixed selectivity per equality column, so a per-type +/// partial index always beats the general (FullTypeName, Partition) index for the +/// property it covers, whatever the data looks like. Statistics can only make that choice +/// worse: a sample of the type-ordered general index sees only the smallest types and +/// credits every type with a handful of rows, while a sample of the partial index sits +/// inside one key and credits every key with hundreds, and the planner then reads every +/// row of the type on each lookup (5.3.1). /// /// [TestClass] @@ -40,11 +40,8 @@ public class PlannerStatisticsTests private const int RowsPerGroup = 100; private const int WideRowCount = GroupCount * RowsPerGroup; - private const int BucketCount = 8; - private const string GroupIndexName = "group_idx"; private const string SeqIndexName = "seq_idx"; - private const string BucketIndexName = "bucket_idx"; private const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; private const string LookupGroup = "G0042"; @@ -58,8 +55,6 @@ public class WideModel public int Seq { get; set; } - public int Bucket { get; set; } - public string Label { get; set; } } @@ -83,7 +78,7 @@ public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexChosen( (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - AssertFullStatistics(dbFile, GroupIndexName); + ReadStatRows(dbFile).ShouldBeEmpty(); AssertGroupLookupUsesPartialIndex(dbFile); } @@ -93,15 +88,12 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() var (path, dbName) = NewDbPath(); var dbFile = Path.Combine(path, dbName); - // Launch 1: the app declares its index before any data exists; statistics - // gathered on an empty type are not kept. + // Launch 1: the app declares its index before any data exists. using (var db = await BuildDb(path, dbName).ConnectAsync()) { await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); } - ReadStatRows(dbFile).ShouldBeEmpty(); - SeedSmallTypes(dbFile); // Launch 2: a sync loads the large type, then the app closes. @@ -110,8 +102,7 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() await db.WriteObjectsAsync(WideRows(), x => x.Key); } - // Launch 3: the index is re-declared; it has rows now but no statistics, so - // they are gathered before the query runs. + // Launch 3: the index is re-declared (a no-op) and queried. using (var db = await BuildDb2(path, dbName).ConnectAsync()) { await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); @@ -119,136 +110,33 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); } - AssertFullStatistics(dbFile, GroupIndexName); - AssertGroupLookupUsesPartialIndex(dbFile); - } - - [TestMethod] - public async Task Connect_RepairsSampledStatisticsLeftByAnEarlierRelease() - { - var dbFile = await SeedIndexedStore(); - var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); - - LeaveSampledStatistics(dbFile); - Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); - - using (var db = await BuildDb2(path, dbName).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - - ReadUserVersion(dbFile).ShouldBe(1); - AssertFullStatistics(dbFile, GroupIndexName); - AssertGroupLookupUsesPartialIndex(dbFile); - } - - [TestMethod] - public async Task Connect_WithAutoOptimizeOff_LeavesStatisticsUntilOptimize() - { - var dbFile = await SeedIndexedStore(); - var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); - - LeaveSampledStatistics(dbFile); - var sampled = ReadStatRows(dbFile); - - // Connect leaves the store exactly as the previous release did. - using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) - { - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - - ReadUserVersion(dbFile).ShouldBe(0); - ReadStatRows(dbFile).ShouldBe(sampled); - Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); - - // Optimize does the repair instead, once. - using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) - { - (await db.OptimizeAsync()).ShouldBeTrue(); - } - - ReadUserVersion(dbFile).ShouldBe(1); - AssertFullStatistics(dbFile, GroupIndexName); - AssertGroupLookupUsesPartialIndex(dbFile); - } - - [TestMethod] - public async Task Connect_OnStoreWithoutIndexes_DiscardsStatisticsAndStamps() - { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - using (var db = await BuildDb(path, dbName).ConnectAsync()) - { - await db.WriteObjectsAsync(WideRows(), x => x.Key); - } - - LeaveSampledStatistics(dbFile); - ReadStatRows(dbFile).ShouldNotBeEmpty(); - - using (await BuildDb2(path, dbName).ConnectAsync()) - { - } - - // Nothing to rank, so nothing to keep: the rows are discarded rather than analyzed. ReadStatRows(dbFile).ShouldBeEmpty(); - ReadUserVersion(dbFile).ShouldBe(1); - } - - [TestMethod] - public async Task FreshStore_IsStampedAndHasNoStatisticsTable() - { - var (path, dbName) = NewDbPath(); - var dbFile = Path.Combine(path, dbName); - - using (await BuildDb(path, dbName).ConnectAsync()) - { - } - - ReadUserVersion(dbFile).ShouldBe(1); - StatisticsTableExists(dbFile).ShouldBeFalse(); + AssertGroupLookupUsesPartialIndex(dbFile); } [TestMethod] - public async Task Connect_OnCurrentStore_WritesNothing() + public async Task Connect_RemovesStatisticsLeftByAnEarlierRelease() { - var dbFile = await SeedIndexedStore(); - var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); - - var schemaVersion = ReadSchemaVersion(dbFile); - var statRows = ReadStatRows(dbFile); - - for (int i = 0; i < 3; i++) + foreach (var autoOptimize in new[] { true, false }) { - using var db = await BuildDb2(path, dbName).ConnectAsync(); - await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); - await db.CreateIndexAsync(x => x.Seq, SeqIndexName); - (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); - } - - ReadSchemaVersion(dbFile).ShouldBe(schemaVersion); - ReadStatRows(dbFile).ShouldBe(statRows); - ReadUserVersion(dbFile).ShouldBe(1); - } + var dbFile = await SeedIndexedStore(); + var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); - [TestMethod] - public async Task TwoIndexedEqualities_UseTheMoreSelectiveIndex_InEitherCreationOrder() - { - foreach (var selectiveFirst in new[] { true, false }) - { - var dbFile = await SeedIndexedStore(seqIndexFirst: selectiveFirst); + LeaveSampledStatistics(dbFile); + Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); - // Seq is unique; GroupId has 100 rows per value. Without statistics the planner - // takes whichever partial index was created last. - var plan = Explain(dbFile, filter: GroupFilter().And().Filter(FilterType.Equals, x => x.Seq, 42)); + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } - plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", Case.Sensitive, $"seqIndexFirst: {selectiveFirst}"); - plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); } } [TestMethod] - public async Task WithStatistics_EqualityUsesThePartialIndex() + public async Task WithoutStatistics_EqualityUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); @@ -259,7 +147,7 @@ public async Task WithStatistics_EqualityUsesThePartialIndex() } [TestMethod] - public async Task WithStatistics_RangeUsesThePartialIndex() + public async Task WithoutStatistics_RangeUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); @@ -272,7 +160,7 @@ public async Task WithStatistics_RangeUsesThePartialIndex() } [TestMethod] - public async Task WithStatistics_SortWithLimitUsesThePartialIndex() + public async Task WithoutStatistics_SortWithLimitUsesThePartialIndex() { var dbFile = await SeedIndexedStore(); @@ -287,51 +175,46 @@ public async Task WithStatistics_SortWithLimitUsesThePartialIndex() } [TestMethod] - public async Task WithStatistics_NonSelectiveIndexedEqualityUsesThePartialIndex() + public async Task WithoutStatistics_TwoIndexedEqualitiesUseOneOfThePartialIndexes() { var dbFile = await SeedIndexedStore(); - // One of eight values: 2,500 rows, an eighth of the table. The general index's - // pinned row says half, so the partial index still wins. - var plan = Explain(dbFile, filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Bucket, 3)); + var plan = Explain( + dbFile, + filter: GroupFilter().And().Filter(FilterType.Equals, x => x.Seq, 42)); - plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, BucketIndexName)}", Case.Sensitive); + var partialIndexes = new[] + { + $"USING INDEX {ReadPhysicalIndexName(dbFile, GroupIndexName)}", + $"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", + }; + + partialIndexes.Count(name => plan.Contains(name, StringComparison.Ordinal)).ShouldBe(1); plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } [TestMethod] - public async Task WithStatistics_UnindexedPropertyUsesTheGeneralIndex() + public async Task WithoutStatistics_UnindexedPropertyUsesTheGeneralIndex() { var dbFile = await SeedIndexedStore(); - var filter = FilterBuilder.Create().Filter(FilterType.Equals, x => x.Label, "row 7"); + var plan = Explain( + dbFile, + filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Label, "row 7")); - Explain(dbFile, filter: filter).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); - Explain(dbFile, filter: filter, fullTypeName: SmallTypeName(0)).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + plan.ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); } [TestMethod] - public async Task WithStatistics_WholeTypeUsesTheGeneralIndex() + public async Task WithoutStatistics_WholeTypeUsesTheGeneralIndex() { var dbFile = await SeedIndexedStore(); - // The wide type is 98% of the table and the small type 0.05%; both are reached - // through the general index, never by a scan, whatever ANALYZE averaged. Explain(dbFile).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); - Explain(dbFile, fullTypeName: SmallTypeName(0)).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); - } - - [TestMethod] - public async Task Statistics_GeneralIndexRowIsPinnedToHalfTheTable() - { - var dbFile = await SeedIndexedStore(); - - // Statistics were gathered when the wide type was the whole table. - ReadStatRows(dbFile).ShouldContain($"JsonValue {GeneralIndexName} {WideRowCount} {WideRowCount / 2} {WideRowCount / 2}"); } [TestMethod] - public async Task WithStatistics_CountUsesTheGeneralIndexWithoutReadingRows() + public async Task WithoutStatistics_CountUsesTheGeneralIndexWithoutReadingRows() { var dbFile = await SeedIndexedStore(); @@ -347,38 +230,6 @@ private static void AssertGroupLookupUsesPartialIndex(string dbFile) plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); } - /// The index has a full statistics row: the type's true row count, not a 400-row sample. - private static void AssertFullStatistics(string dbFile, string indexName) - { - var physicalName = ReadPhysicalIndexName(dbFile, indexName); - var row = ReadStatRows(dbFile).SingleOrDefault(r => r.StartsWith($"JsonValue {physicalName} ", StringComparison.Ordinal)); - - row.ShouldNotBeNull($"no statistics row for {physicalName}"); - row.ShouldStartWith($"JsonValue {physicalName} {WideRowCount} "); - } - - private static long ReadUserVersion(string dbFile) => ReadPragma(dbFile, "user_version"); - - private static long ReadSchemaVersion(string dbFile) => ReadPragma(dbFile, "schema_version"); - - private static long ReadPragma(string dbFile, string pragma) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); -#pragma warning disable CA2100 // Pragma name is a test constant. - command.CommandText = "PRAGMA " + pragma; -#pragma warning restore CA2100 - return (long)command.ExecuteScalar(); - } - - private static bool StatisticsTableExists(string dbFile) - { - using var conn = OpenInspection(dbFile); - using var command = conn.CreateCommand(); - command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; - return command.ExecuteScalar() is not null; - } - private static FilterBuilder GroupFilter() => FilterBuilder.Create().Filter(FilterType.Equals, x => x.GroupId, LookupGroup); @@ -388,8 +239,7 @@ private static string Explain( FilterBuilder filter = null, SortBuilder sort = null, int? top = null, - bool count = false, - string fullTypeName = null) + bool count = false) { var sb = new StringBuilder(count ? Queries.SelectCountFromJsonValueWithFullTypeName : Queries.SelectDataFromJsonValueWithFullTypeName); var parameters = new FilterParameters(); @@ -409,7 +259,7 @@ private static string Explain( command.CommandText = "EXPLAIN QUERY PLAN " + sb; #pragma warning restore CA2100 - command.Parameters.AddWithValue("$fullTypeName", fullTypeName ?? typeof(WideModel).FullName); + command.Parameters.AddWithValue("$fullTypeName", typeof(WideModel).FullName); command.Parameters.AddWithValue("$partition", string.Empty); for (int i = 0; i < parameters.Count; i++) { @@ -437,7 +287,7 @@ private static string ReadPhysicalIndexName(string dbFile, string indexName) return (string)command.ExecuteScalar(); } - /// Every statistics row in the store, as "tbl idx stat". + /// Every statistics row in the store; connecting leaves sqlite_stat1 behind, empty. private static List ReadStatRows(string dbFile) { var rows = new List(); @@ -463,26 +313,15 @@ private static List ReadStatRows(string dbFile) // ---------- seeding ---------- /// A store with the wide type indexed on GroupId and Seq, and the small types ahead of it. - private static async Task SeedIndexedStore(bool seqIndexFirst = false) + private static async Task SeedIndexedStore() { var (path, dbName) = NewDbPath(); using (var db = await BuildDb(path, dbName).ConnectAsync()) { await db.WriteObjectsAsync(WideRows(), x => x.Key); - - if (seqIndexFirst) - { - await db.CreateIndexAsync(x => x.Seq, SeqIndexName); - await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); - } - else - { - await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); - await db.CreateIndexAsync(x => x.Seq, SeqIndexName); - } - - await db.CreateIndexAsync(x => x.Bucket, BucketIndexName); + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); + await db.CreateIndexAsync(x => x.Seq, SeqIndexName); } var dbFile = Path.Combine(path, dbName); @@ -490,15 +329,12 @@ private static async Task SeedIndexedStore(bool seqIndexFirst = false) return dbFile; } - /// - /// Leaves what 5.3.1 left: statistics sampled at 400 rows per index, and no - /// user_version stamp. - /// + /// Leaves what 5.3.1 left: statistics sampled at 400 rows per index. private static void LeaveSampledStatistics(string dbFile) { using var conn = OpenInspection(dbFile); using var command = conn.CreateCommand(); - command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE; PRAGMA user_version = 0;"; + command.CommandText = "PRAGMA analysis_limit = 400; ANALYZE;"; command.ExecuteNonQuery(); } @@ -507,7 +343,7 @@ private static List WideRows() var rows = new List(WideRowCount); for (int i = 0; i < WideRowCount; i++) { - rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i, Bucket = i % BucketCount, Label = $"row {i}" }); + rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i, Label = $"row {i}" }); } return rows; @@ -516,9 +352,6 @@ private static List WideRows() private static string GroupId(int i) => "G" + (i % GroupCount).ToString("D4", System.Globalization.CultureInfo.InvariantCulture); - private static string SmallTypeName(int t) - => "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); - private static void SeedSmallTypes(string dbFile) { using var conn = OpenInspection(dbFile); @@ -534,7 +367,7 @@ private static void SeedSmallTypes(string dbFile) for (int t = 0; t < SmallTypeCount; t++) { - fullTypeName.Value = SmallTypeName(t); + fullTypeName.Value = "Aaa.Small" + t.ToString("D2", System.Globalization.CultureInfo.InvariantCulture); for (int i = 0; i < RowsPerSmallType; i++) { key.Value = "small-" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 5c47c0c..ce396cf 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -64,6 +64,16 @@ CREATE TABLE IF NOT EXISTS TychoIndex PRIMARY KEY (IndexName, FullTypeName) ); + -- The planner chooses the right index for every query TychoDB emits on its + -- default heuristics, and statistics only mislead it: a sample of the + -- type-ordered general index credits every type with a handful of rows, and + -- the planner then reads every row of a type on each indexed lookup. Earlier + -- releases gathered them. Whatever an ANALYZE left behind is dropped, and the + -- reload makes this connection forget what it read at open; it leaves an empty + -- sqlite_stat1 behind. + DROP TABLE IF EXISTS sqlite_stat1; + DROP TABLE IF EXISTS sqlite_stat4; + ANALYZE sqlite_master; """; // Indexes earlier versions created that duplicate either the primary-key autoindex @@ -575,95 +585,6 @@ public static string EscapeSqlLiteral(string value) public static string DropIndex(string fullIndexName) => string.Concat(DropIndexPrefix, fullIndexName, ";"); - // ---- Planner statistics ---- - // - // Statistics exist for one decision: ranking two per-type partial indexes against - // each other when a query filters on both of their properties. Without a - // sqlite_stat1 row for each, the planner cannot tell which is more selective and - // takes the one created last; with rows gathered by a *sampled* ANALYZE - // (analysis_limit > 0) it is actively misled, because a sample of the type-ordered - // general index credits every type with a handful of rows while a sample of a - // partial index sits inside one key and credits every key with hundreds, and the - // planner then reads every row of the type on each indexed lookup (5.0.1–5.3.1). - // So statistics are gathered in full, for the one table that carries expression - // indexes, and only when an index is built or found to have none; nothing samples, - // and nothing runs at connect once a store has been repaired. - - // Full statistics for JsonValue, then two corrections and a reload. analysis_limit = 0 - // lifts any limit a caller set on the connection; neither ANALYZE nor a write to - // sqlite_stat1 changes schema_version. - // - // 1. Rows gathered while a type (or the table) was empty read "0 0 0" and are - // removed: the planner does better on its defaults than on "no rows", and a - // missing row is what makes CreateIndex gather statistics again once the type - // has rows. - // 2. The general index's row is pinned to "N N/2 N/2". ANALYZE writes the average - // rows per FullTypeName, and that average is wrong for every type in a store - // where one type dominates: taken while few types existed it says a type is the - // whole table and the planner scans instead of seeking, taken over many it says a - // big type is small and the planner prefers the general index to that type's - // partial index (the mechanism of the sampled-statistics regression, in a milder - // form). N/2 keeps the general index cheaper than a scan for any type (a scan - // costs about 3N in the planner's model, an index visit between 1.1 and 3 per - // row) and more expensive than a partial index for any equality whose value - // repeats on fewer than half the rows, any one-sided range (estimated at a - // quarter of the index without stat4) and any sort with a limit, which leaves the - // partial indexes' own rows — the accurate ones — to rank against each other. - // SQLite documents writing sqlite_stat1 for this purpose - // (https://www.sqlite.org/lang_analyze.html). - public const string AnalyzeJsonValue = - """ - PRAGMA analysis_limit = 0; - ANALYZE JsonValue; - DELETE FROM sqlite_stat1 WHERE tbl = 'JsonValue' AND (stat = '0' OR stat LIKE '0 %'); - UPDATE sqlite_stat1 - SET stat = CAST(stat AS INTEGER) || ' ' || max(CAST(stat AS INTEGER) / 2, 1) || ' ' || max(CAST(stat AS INTEGER) / 2, 1) - WHERE tbl = 'JsonValue' AND idx = 'idx_jsonvalue_fulltypename_partition'; - ANALYZE sqlite_master; - """; - - // SQLite's documented way to make an open connection re-read sqlite_stat1 - // (https://www.sqlite.org/lang_analyze.html). - public const string ReloadStatistics = "ANALYZE sqlite_master;"; - - // Discards every statistics row (sampled rows from an earlier release, or a - // caller's own ANALYZE) and reloads. Used only when the store has no expression - // index, so there is nothing for statistics to rank. The rows are deleted rather - // than the table dropped: the reload would recreate it anyway, and a DELETE is not - // a schema change. - public const string DropStatistics = - """ - DELETE FROM sqlite_stat1; - DROP TABLE IF EXISTS sqlite_stat4; - ANALYZE sqlite_master; - """; - - public const string StatisticsTableExists = - "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1';"; - - public const string CountIndexMetadata = "SELECT COUNT(*) FROM TychoIndex;"; - - // The stat1 row for one physical index: " ...". NULL - // when the index has never been analyzed, or was analyzed while its type was empty. - public const string SelectIndexStatistics = - "SELECT stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' AND idx = $physicalName;"; - - // Whether a type has any rows at all; one probe of the general index. - public const string TypeHasRows = - "SELECT 1 FROM JsonValue WHERE FullTypeName = $fullTypeName LIMIT 1;"; - - // PRAGMA user_version of a store whose statistics are known to be unsampled: either - // repaired once by this release or created by it. A store written by an earlier - // release reads 0 and may carry sampled rows, which the connect-time repair - // replaces or discards exactly once before stamping; a stamped store does nothing - // at connect. The literal is the single source of both the stamp and the value - // compared against. - public const string StatisticsUserVersion = "1"; - - public const string UserVersion = "PRAGMA user_version;"; - - public const string StampStatisticsUserVersion = "PRAGMA user_version = " + StatisticsUserVersion + ";"; - public const string SelectIndexMetadata = """ SELECT PhysicalName, Definition, ShapeVersion diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index d1e831b..f4c87c2 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -47,7 +47,6 @@ private const string private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; - private readonly bool _autoOptimize; // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -106,16 +105,11 @@ private const string /// Optional override for the SQLite page cache size, in KiB. Overrides the profile default. /// Optional override for the SQLite memory-map size, in bytes (0 disables mmap). Overrides the profile default. /// - /// Whether connecting performs one-time store maintenance on the connecting thread: - /// dropping the redundant indexes 4.x created, and replacing the sampled planner - /// statistics 5.0.1–5.3.1 left behind with full ones (or discarding them when the - /// store has no expression index). Both run once per store; a store that is already - /// current pays a single header read at connect. The index drops took 10–30 s on a - /// large store upgraded from 4.x, and a full ANALYZE is proportional to the - /// store's size, so pass false to connect without either and call - /// or from a background thread - /// at a convenient time; until then an upgraded store keeps the plans it had on the - /// previous release. Default is true. + /// Whether connecting drops the redundant indexes 4.x created. Freeing their pages + /// runs on the connecting thread and took 10–30 s on a large store upgraded from + /// 4.x; pass false to connect without it and call or + /// from a background thread at a convenient time, which + /// does the same work. Default is true. /// public Tycho( string dbPath, @@ -167,7 +161,6 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; - _autoOptimize = autoOptimize; _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize); } @@ -2218,165 +2211,58 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) /// from any previous shape or name for the same logical index. /// /// Mobile apps typically call CreateIndex on every launch, so the already-current - /// case must be cheap: it costs one metadata lookup, one sqlite_master probe and - /// one statistics lookup, with no DDL. Building an index, or re-declaring one that - /// was built while its type was empty and now has rows, gathers full planner - /// statistics for JsonValue so the index is ranked correctly against the type's - /// other indexes from the very next query; see . + /// case must be cheap: it costs one metadata lookup and one sqlite_master probe, + /// with no DDL. /// /// private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) { - bool gatherStatistics; - - using (var transaction = conn.BeginTransaction(IsolationLevel.Serializable)) - { - try - { - if (IsIndexCurrent(conn, definition)) - { - gatherStatistics = IndexLacksStatistics(conn, definition); - transaction.Commit(); - } - else - { - // Drop the previously recorded physical index (shape or definition - // changed) and any pre-metadata index that used the legacy name, so an - // upgraded database does not keep maintaining a stale b-tree forever. - foreach (var stalePhysicalName in ReadRecordedPhysicalNames(conn, definition)) - { - ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); - } - - if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) - { - ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); - } - - ExecuteNonQuery(conn, definition.CommandText); - - using (var upsert = conn.CreateCommand()) - { - upsert.CommandText = Queries.UpsertIndexMetadata; - upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); - upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); - upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); - upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definition.CommandText }); - upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = IndexShapeVersion }); - upsert.ExecuteNonQuery(); - } - - transaction.Commit(); - gatherStatistics = true; - } - } - catch (Exception ex) - { - transaction.Rollback(); - throw new TychoException($"Failed to Create Index: {definition.PhysicalName}", ex); - } - } + using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); - if (gatherStatistics) + try { - // Outside the transaction, so the index is committed whatever happens here. - // Advisory: statistics are an optimization, not a correctness requirement. - try + if (IsIndexCurrent(conn, definition)) { - ExecuteNonQuery(conn, Queries.AnalyzeJsonValue); - } - catch - { - // A read-only file or medium cannot take statistics; the index still works. + transaction.Commit(); + return true; } - } - - return true; - } - - /// - /// True when a current index has no statistics row although its type has rows: it - /// was never analyzed, or it was built while the type was empty (that row is not - /// kept, see ) and the data arrived later. - /// Either leaves the planner unable to rank this index against the type's other - /// indexes. The probe for rows is scoped to the type, so this only ever applies to - /// the per-type partial indexes the expression overloads create. - /// - private static bool IndexLacksStatistics(SqliteConnection conn, IndexDefinition definition) - { - using var command = conn.CreateCommand(); - command.CommandText = Queries.StatisticsTableExists; - - if (command.ExecuteScalar() is not null) - { - command.CommandText = Queries.SelectIndexStatistics; - command.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); - if (command.ExecuteScalar() is not null) + // Drop the previously recorded physical index (shape or definition + // changed) and any pre-metadata index that used the legacy name, so an + // upgraded database does not keep maintaining a stale b-tree forever. + foreach (var stalePhysicalName in ReadRecordedPhysicalNames(conn, definition)) { - return false; + ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); } - command.Parameters.Clear(); - } - - command.CommandText = Queries.TypeHasRows; - command.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); - return command.ExecuteScalar() is not null; - } - - /// - /// One-time repair of the planner statistics an earlier release left in the store, - /// keyed on PRAGMA user_version so a current store pays one header read and - /// writes nothing. A store below may hold - /// rows sampled with analysis_limit = 400, which mislead the planner into the - /// general index (5.0.1–5.3.1): when the store has expression indexes they are - /// replaced by full statistics, otherwise they are discarded, since statistics only - /// serve to rank one expression index against another. The store is then stamped. - /// Best-effort: failures never block connect. - /// - private static void RepairStatistics(SqliteConnection conn) - { - try - { - using var command = conn.CreateCommand(); - command.CommandText = Queries.UserVersion; - long userVersion = command.ExecuteScalar() is long version ? version : 0L; - - if (userVersion >= StatisticsUserVersion) + if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) { - return; + ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); } - command.CommandText = Queries.CountIndexMetadata; - bool hasExpressionIndexes = command.ExecuteScalar() is long count && count > 0; + ExecuteNonQuery(conn, definition.CommandText); - if (hasExpressionIndexes) + using (var upsert = conn.CreateCommand()) { - command.CommandText = Queries.AnalyzeJsonValue; - command.ExecuteNonQuery(); - } - else - { - command.CommandText = Queries.StatisticsTableExists; - if (command.ExecuteScalar() is not null) - { - command.CommandText = Queries.DropStatistics; - command.ExecuteNonQuery(); - } + upsert.CommandText = Queries.UpsertIndexMetadata; + upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); + upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); + upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); + upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definition.CommandText }); + upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = IndexShapeVersion }); + upsert.ExecuteNonQuery(); } - command.CommandText = Queries.StampStatisticsUserVersion; - command.ExecuteNonQuery(); + transaction.Commit(); } - catch + catch (Exception ex) { - // Statistics are an optimization, not a correctness requirement. + transaction.Rollback(); + throw new TychoException($"Failed to Create Index: {definition.PhysicalName}", ex); } - } - private static readonly long StatisticsUserVersion = - long.Parse(Queries.StatisticsUserVersion, System.Globalization.CultureInfo.InvariantCulture); + return true; + } /// /// True when the recorded definition matches what would be created now and the @@ -2721,17 +2607,15 @@ public IReadOnlyList ListIndexes() /// /// Does what connecting does on its own when autoOptimize is on: drops the - /// redundant indexes 4.x created and, once per store, replaces the sampled planner - /// statistics 5.0.1–5.3.1 left behind with full ones (or discards them when the store - /// has no expression index). A no-op once both are done, so calling it on every - /// launch is fine. + /// redundant indexes 4.x created. A no-op once they are gone, so calling it on + /// every launch is fine. /// /// Holds the database's single connection for the duration, so every other /// operation on this instance waits: freeing the indexes' pages took 10–30 s on a - /// large store upgraded from 4.x, and a full ANALYZE reads every index of - /// JsonValue once. The work runs on the calling thread — Microsoft.Data.Sqlite - /// executes synchronously, so does not move it off the - /// caller by itself — and must not be called from a UI thread. + /// large store upgraded from 4.x. The work runs on the calling thread — + /// Microsoft.Data.Sqlite executes synchronously, so + /// does not move it off the caller by itself — and must not be called from a UI + /// thread. /// /// public void Optimize() @@ -2768,7 +2652,6 @@ public ValueTask OptimizeAsync(CancellationToken cancellationToken = defau private static bool OptimizeStore(SqliteConnection conn) { ExecuteNonQuery(conn, Queries.DropLegacyIndexes); - RepairStatistics(conn); return true; } @@ -3095,29 +2978,23 @@ private SqliteConnection BuildConnection() connection .WithConnectionBlock( _connectionGate, - (Script: _connectionScript, AutoOptimize: _autoOptimize), - static (conn, state) => + _connectionScript, + static (conn, script) => { conn.Open(); // Verified once per process (see EnsureJsonSupport). EnsureJsonSupport(conn); - using (var command = conn.CreateCommand()) - { - // Profile PRAGMAs + idempotent schema/index creation. Composed from - // library constants and numeric profile values only (no user input). + using var command = conn.CreateCommand(); + + // Profile PRAGMAs + idempotent schema/index creation. Composed from + // library constants and numeric profile values only (no user input). #pragma warning disable CA2100 - command.CommandText = state.Script; + command.CommandText = script; #pragma warning restore CA2100 - command.ExecuteNonQuery(); - } - - if (state.AutoOptimize) - { - RepairStatistics(conn); - } + command.ExecuteNonQuery(); }, _persistConnection); @@ -3148,11 +3025,6 @@ private async ValueTask BuildConnectionAsync(CancellationToken command.ExecuteNonQuery(); - if (_autoOptimize) - { - RepairStatistics(connection); - } - return connection; } finally diff --git a/docs/indexing-analysis.md b/docs/indexing-analysis.md index 1eaf83f..deebbb7 100644 --- a/docs/indexing-analysis.md +++ b/docs/indexing-analysis.md @@ -124,10 +124,6 @@ win; the query-plan sweep in that bucket must confirm no query regresses to a ta ## 5. Statistics -> **5.4.0:** the bounded `ANALYZE` and `PRAGMA optimize` this section led to sampled the -> indexes and misled the planner; see `docs/planner-statistics-sampling.md` for the -> regression and the design that replaced them. - `sqlite_stat1` does not exist even after a full connect→index-create→dispose cycle — `Disconnect`'s `PRAGMA optimize` produced no statistics table in the diagnose run. All plans above are chosen by default heuristics. Bucket 3 adds a bounded `ANALYZE` after diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index 2d94b99..87260f3 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -1,4 +1,4 @@ -# Sampled planner statistics made SQLite skip the partial indexes (5.0.1–5.3.1) +# Sampled planner statistics made SQLite skip the partial indexes (5.3.1) ## Symptom @@ -20,9 +20,10 @@ ON JsonValue (Partition, JSON_EXTRACT(Data, '$.GroupId')) WHERE FullTypeName = 'Zzz.Models.WideModel'; ``` -5.0.1 started running `PRAGMA optimize` on connect and disconnect, and 5.1.1 added an -`ANALYZE` after `CreateIndex`; both set `PRAGMA analysis_limit = 400`. With a limit, -`ANALYZE` reads only the first ~400 entries of each index: +5.3.0 started gathering planner statistics, and 5.3.1 gathered them with +`PRAGMA analysis_limit = 400` (`PRAGMA optimize` on connect, disconnect and dispose, and +`ANALYZE` after `CreateIndex`). With a limit, `ANALYZE` reads only the first ~400 entries of +each index: - The general index is ordered by type name, and the types that sort first are tiny (22, 112, 10, 202 rows… in the real store). Its sample spans a handful of types, so @@ -35,134 +36,78 @@ every row of the type on each lookup. ## Fix -Statistics are kept, gathered in full, and owned by TychoDB. - -- **When.** `CreateIndex` runs `PRAGMA analysis_limit = 0; ANALYZE JsonValue;` after it - builds an index, and again when it re-declares an index that was built while its type - was empty and has rows now (a re-declared index that is current and has a statistics - row costs one metadata lookup, one `sqlite_master` probe and one `sqlite_stat1` lookup, - no DDL). Nothing else gathers statistics: `PRAGMA optimize` is gone from connect, - disconnect and dispose. -- **What.** `ANALYZE JsonValue` only — the one table with expression indexes. Rows - recorded for an empty type (`0 0 0`) are deleted, so the planner uses its defaults - until the type has rows and the index is re-declared. The general index's row is then - pinned to `N N/2 N/2` and the connection reloads with `ANALYZE sqlite_master`. -- **Why pin.** `ANALYZE` writes the general index's row as the *average* rows per - `FullTypeName`, and in a store where one type dominates that average is wrong for every - type: taken while few types existed it says a type is the whole table and the planner - scans instead of seeking (every read of a ten-row settings type scans the 586,986-row - type); taken over many types it says the big type is small, and the planner prefers the - general index to that type's partial index — the sampled-statistics regression again, - in a milder form. In the planner's model a scan costs about 3N and an index visit - between 1.1 and 3 per row, so N/2 keeps the general index cheaper than a scan for any - type; and it is dearer than a partial index for any equality whose value repeats on - fewer than half the rows, any one-sided range (estimated at a quarter of the index - without stat4) and any sort with a limit. That leaves the partial indexes' own rows, - which are accurate, to rank against each other — the one thing statistics are for. - SQLite documents writing `sqlite_stat1` for this purpose - (https://www.sqlite.org/lang_analyze.html, "Manual Control Of Query Plans"). -- **Upgraded stores.** `PRAGMA user_version` gates a one-time repair: a store below the - stamp may carry sampled rows, so when `autoOptimize` is on the first connect replaces - them (full `ANALYZE` if the store has expression indexes, otherwise it discards them — - statistics only rank one expression index against another) and stamps the store. A - stamped store pays one header read at connect and writes nothing; `schema_version` is - stable across reconnects. With `autoOptimize: false`, connect leaves the store as the - previous release did and `Optimize()` / `OptimizeAsync()` performs the repair. - -Plans on the 20,400-row test store (40 small types, one type with 20,000 rows over 200 -keys, indexed on `GroupId`, a unique `Seq` and an 8-value `Bucket`), asserted by -`TychoDB.UnitTests/PlannerStatisticsTests.cs` on both bundled engines (SQLite 3.50.3 and -SQLCipher's 3.39.2): - -| Query | Plan | -|---|---| -| equality on an indexed property (100 of 20,000) | partial index | -| equality on a non-selective indexed property (2,500 of 20,000) | partial index | -| range on an indexed numeric property | partial index | -| sort on an indexed numeric property, `LIMIT 20` | partial index, no temp b-tree | -| two indexed equalities, unique index created first **or** last | the unique index | -| equality on an unindexed property, wide type and small type | general index | -| whole type, wide (98% of the table) and small (0.05%) | general index | -| count | general index, covering | - -## Why not "no statistics" - -This branch tried both of the other designs before landing here. - -*No statistics at all* (the connect script dropped `sqlite_stat1`) gets every single-index -shape right on the planner's defaults, and removes every way statistics can go stale or -inconsistent. But with two partial indexes on one type and a filter on both properties -the planner has nothing to rank them by and takes whichever was created last: measured -through `ReadObjectsAsync` at 40,000 rows, 0.022 ms → 4.56 ms (plain) and 0.019 ms → -57.5 ms (SQLCipher, where every extra page is decrypted) for a one-row result when the -less selective index came second. Which order a store ends up in is whatever order the -app first declared its indexes, so the regression is silent and permanent. - -*Full statistics as `ANALYZE` writes them*, with `PRAGMA optimize` to keep them fresh, -was the branch's first design and ran into: - -- `PRAGMA optimize`'s default mask includes bit `0x10`, a temporary 2,000-row limit - regardless of `analysis_limit`, so it wrote `2001 501` against `101` and mis-ranked the - indexes the same way (repro case 4). -- `PRAGMA optimize(0x10002)` lifts the limit but decides whether a table has grown from - the cell counts down the leftmost path of its b-tree. A 2.2 GB production store (1.84M - rows, estimated at 174,370) was re-analyzed on every call, 20–30 s each, because its - lowest rowids held large documents. -- A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on the 2.2 GB store, on - the connecting thread. -- The general index's averaged row misled the planner in both directions, as described - under *Why pin*. - -The design above keeps the full `ANALYZE` but runs it only where its result is used (an -index was built) or deferrable (`Optimize`), never on a timer or at every connect, and -removes the one row that `ANALYZE` gets wrong. - -## Cost - -- Connect on a current store: one `PRAGMA user_version` read. No DDL, no write. -- `CreateIndex` of a current index with statistics: one extra `sqlite_stat1` lookup. -- `CreateIndex` that builds an index, or re-declares one built on an empty type that has - rows now: a full `ANALYZE JsonValue`, proportional to the store (0.115 s at 544k rows - in the CLI repro; 3.2 s / 17.5 s on the production stores above). -- First connect of a store written by 5.0.1–5.3.1 with `autoOptimize` on: the same full - `ANALYZE` once if it has expression indexes, otherwise a `DELETE` of its statistics - rows; then the stamp. - -The four `DROP INDEX IF EXISTS` for the indexes 4.x created were most of a 10–30 s stall -measured on the first launch of a large upgraded store (main-thread samples in -`sqlite3BtreeDropTable`/`clearDatabasePage`): freeing an index's pages is proportional to -its size, and with `secure_delete` on — SQLCipher's default — every freed page is written -back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6–7 ms each -plain and 39–54 ms each with `secure_delete`. They stay on by default, because they make -bulk writes 25–45% faster; `autoOptimize: false` connects without them and -`Optimize`/`OptimizeAsync` run them later. Both hold the single connection for the -duration and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so -the async form alone does not move the work off the caller — so apps call them from a -background thread. `CreateIndex` itself drops a per-type legacy index and builds the -partial one, which is the other piece of an upgrade stall and already under the app's -control through when it calls it. +TychoDB gathers no statistics, and removes any it finds. The connect script ends with +`DROP TABLE IF EXISTS sqlite_stat1; DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master;` +— the last statement is SQLite's documented way to reload statistics on an open connection, +and it leaves an empty `sqlite_stat1` behind. Nothing else runs `ANALYZE` or +`PRAGMA optimize`. The one-time index drops stay, behind `autoOptimize` and `Optimize`. + +Without a `sqlite_stat1` row, SQLite's planner credits a partial index with half the table +and every index with a fixed selectivity per equality column, so the per-type partial index +beats the general index for the property it covers whatever the data looks like. Every +query shape TychoDB emits gets the right plan on the 544k-row synthetic store, on both +bundled engines (3.50.4 and SQLCipher's 3.39.2; the tests in +`TychoDB.UnitTests/PlannerStatisticsTests.cs` assert each one): + +| Query | Plan with no statistics | Time | +|---|---|---| +| equality on an indexed property | partial index | 0–1 ms | +| range on an indexed numeric property | partial index | 1 ms | +| sort on an indexed numeric property, `LIMIT 20` | partial index, no temp b-tree | 0 ms | +| two indexed equalities | one of the two partial indexes, chosen by rule | 0 ms | +| equality on an unindexed property | general index, then filter | 190 ms (reads the type; the only plan there is) | +| whole type | general index | 20 ms | +| count | general index, covering | 20 ms | + +The one thing statistics could add is the choice between two indexed properties filtered +together: without them the planner cannot tell which is more selective and picks one by +rule, so the lookup is bounded by the rows matching that property rather than the smaller +set. On the stores measured so far every indexed property is selective enough for this not +to matter. + +## Why not gather them properly instead + +The branch first did that: a full `ANALYZE` (`analysis_limit = 0`) after `CreateIndex` and +whenever an index had no statistics or a table had grown tenfold, a `user_version` stamp so +stores written by 5.3.1 were re-analyzed once, an opt-out so the connect-time cost could be +deferred, and finally TychoDB's own staleness check. Each layer existed to make gathering +statistics safe, and testing on real stores kept finding the next hole: + +- A full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, on the + connecting thread. +- `PRAGMA optimize`, SQLite's recommended maintenance, cannot be used as is: its default + mask includes bit `0x10`, a temporary 2,000-row limit regardless of `analysis_limit`, so + it wrote `2001 501` against `101` and mis-ranked the indexes the same way (repro case 4). +- `PRAGMA optimize(0x10002)` lifts the limit but decides whether a table has grown from the + cell counts down the leftmost path of its b-tree. A 2.2 GB production store (1.84M rows, + estimated at 174,370) was re-analyzed on every call, 20–30 s each, because its lowest + rowids held large documents. Any store can drift into that layout. +- Statistics gathered on a few hundred rows, then 540,000 rows arriving, are fine; a full + partial-index row next to a stale general-index row is not; a 5.3.1 build writing to a + repaired store brings the sampled rows back undetected. The states that mislead the + planner are the inconsistent ones, and every refresh policy has a window in which the + store is inconsistent. + +With no statistics there is nothing to sample, go stale, half-refresh or roll back, and +plan choice stops depending on data layout or on which release last wrote the file. +`docs/indexing-analysis.md` (5.3.0) listed "planner statistics are never available" as a +defect to fix; the 5.3.0 speedups came from the partial-index redesign, not from the +statistics, and that finding is reversed. ## Repro - `docs/planner-statistics-sampling.sql` — sqlite3 CLI only, synthetic data, ~3 s. Forty tiny types that sort first, one type with 540,000 rows over 1,000 keys, the two partial index shapes. Case 1 is 5.3.1's sampled statistics (general index, ~0.2 s per lookup); - case 2 is no statistics; case 3 is a full `ANALYZE`, the rows TychoDB now gathers before - pinning the general index's row; case 4 is plain `PRAGMA optimize`. + case 2 is what TychoDB now does at connect (the table above); case 3 is a full `ANALYZE` + for comparison; case 4 is plain `PRAGMA optimize`. - `TychoDB.UnitTests/PlannerStatisticsTests.cs` — through Tycho's own `CreateIndexAsync`, - `ConnectAsync`, `OptimizeAsync` and dispose paths on the 20,400-row store: the two - scenarios that failed on 5.3.1 (index created after the data; index created on an empty - type, data loaded, reconnected), a store carrying 5.3.1's sampled rows repaired at - connect and, with `autoOptimize: false`, left alone until `Optimize`, a store without - indexes whose rows are discarded, a fresh store, `schema_version` and the statistics - unchanged across reconnects of a current store, the pinned general-index row, and one - test per query shape in the table above, including both creation orders of the two - partial indexes. -- `TychoDB.Benchmarks/Benchmarks/PlannerStatistics.cs` — the same layout at 40,000 rows - through the public API across three "launches": an indexed equality (the 5.3.1 - regression), two indexed equalities with the unique index created first or last (the - no-statistics regression), and a whole-type read of a ten-row type (the averaged-row - scan). `dotnet run --project TychoDB.Benchmarks -c Release -- --filter '*PlannerStatistics*'`. + `ConnectAsync` and dispose paths on a 20,400-row store (40 small types, one type with + 20,000 rows over 200 keys): the two scenarios that failed on 5.3.1 (index created after + the data, and data loaded after the index then reconnected), a store carrying 5.3.1's + sampled rows repaired on connect with `autoOptimize` on and off, and one test per query + shape in the table above. Each asserts the plan for the library's own SQL and that no + statistics row exists. Bound parameters are fine in the library: SQLite re-plans when a bound value touches a partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic @@ -190,8 +135,8 @@ control through when it calls it. ## Verification -- Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.3) and +- Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and Encrypted (3.39.2). The two scenario tests fail on it in both configurations with `SEARCH JsonValue USING INDEX idx_jsonvalue_fulltypename_partition`. -- Final state: 379 passed, 4 skipped, 0 failed in both configurations. -- Benchmark before/after: see the pull request. +- Final state: 373 passed, 4 skipped, 0 failed in both configurations (Debug 3 s, + Encrypted 1 m 24 s). diff --git a/docs/planner-statistics-sampling.sql b/docs/planner-statistics-sampling.sql index b73d66d..a409c22 100644 --- a/docs/planner-statistics-sampling.sql +++ b/docs/planner-statistics-sampling.sql @@ -1,7 +1,6 @@ -- Sampled ANALYZE (PRAGMA analysis_limit = 400) makes SQLite prefer the general -- (FullTypeName, Partition) index over a per-type partial expression index; with no --- statistics at all, every single-index query shape TychoDB emits picks the right index --- (two indexed filters ANDed do not: see planner-statistics-sampling.md). +-- statistics at all, every query shape TychoDB emits picks the right index. -- -- Usage: rm -f repro.db repro.db-wal repro.db-shm; sqlite3 repro.db < planner-statistics-sampling.sql -- Needs only the sqlite3 CLI (written against 3.51.0). Every row is generated below; no @@ -78,7 +77,7 @@ SELECT count(*), sum(length(Data)) FROM (SELECT rowid, Data FROM JsonValue WHERE -- --------------------------------------------------------------------------- .print -.print '== [2] No statistics: DROP TABLE sqlite_stat1; ANALYZE sqlite_master;' +.print '== [2] No statistics, as TychoDB connects: DROP TABLE sqlite_stat1; ANALYZE sqlite_master;' DROP TABLE IF EXISTS sqlite_stat1; DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master; From 86917c7816d76f367c0a03a9bdcdd2c6c2205d15 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Wed, 14 Oct 2026 19:50:30 -0500 Subject: [PATCH 13/25] fix: open an existing store without the creation-only auto_vacuum pragma --- TychoDB.UnitTests/ConfigurationTests.cs | 11 ++++++++ TychoDB/Queries.cs | 34 +++++++++++++++++-------- TychoDB/Tycho.cs | 25 +++++++++++++++--- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/TychoDB.UnitTests/ConfigurationTests.cs b/TychoDB.UnitTests/ConfigurationTests.cs index 2e0646d..5a9376c 100644 --- a/TychoDB.UnitTests/ConfigurationTests.cs +++ b/TychoDB.UnitTests/ConfigurationTests.cs @@ -59,6 +59,17 @@ public void AutoVacuum_IsSetBeforeJournalMode() autoVacuumIndex.ShouldBeLessThan(journalModeIndex, "auto_vacuum must be set before journal_mode = WAL"); } + [TestMethod] + public void ExistingDatabaseScript_OmitsTheCreationOnlyAutoVacuumPragma() + { + // On an auto-vacuum store the pragma rewrites page 1 at every connect for nothing, + // so a file that already exists is opened without it. + var script = Queries.BuildConnectionScript(TychoPerformanceProfile.Mobile, newDatabase: false); + + script.ShouldNotContain("PRAGMA auto_vacuum"); + script.ShouldContain("PRAGMA journal_mode = WAL;"); + } + [TestMethod] public async Task FreshDatabase_IsCreatedWithIncrementalAutoVacuum() { diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index ce396cf..e6fbd2a 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -9,18 +9,23 @@ internal static class Queries public const string KeyColumn = "Key"; public const string DataColumn = "Data"; + // Incremental auto-vacuum, for a database being created. It MUST be the first + // statement: the mode can only be applied when the database is first created, and + // switching to WAL writes the database header — so if auto_vacuum is set after + // journal_mode = WAL it silently stays at the default (NONE) even on a brand-new + // file, leaving incremental_vacuum a no-op. It is left out when opening an existing + // file: there it either does nothing (a NONE store, until a VACUUM converts it) or + // rewrites page 1 at every connect to store the mode the file already has. + private const string CreationPragma = + """ + PRAGMA auto_vacuum = INCREMENTAL; + """; + // PRAGMAs shared by every profile. These are single-user / single-connection // choices: WAL journaling with EXCLUSIVE locking (one persistent connection), - // NORMAL synchronous (safe under WAL), in-memory temp store, and incremental - // auto-vacuum. - // - // auto_vacuum MUST be the first statement: it can only be applied when the - // database is first created, and switching to WAL writes the database header — - // so if auto_vacuum is set after journal_mode = WAL it silently stays at the - // default (NONE) even on a brand-new file, leaving incremental_vacuum a no-op. + // NORMAL synchronous (safe under WAL), and an in-memory temp store. private const string SharedPragmas = """ - PRAGMA auto_vacuum = INCREMENTAL; PRAGMA journal_mode = WAL; PRAGMA locking_mode = EXCLUSIVE; PRAGMA synchronous = NORMAL; @@ -109,13 +114,15 @@ PRIMARY KEY (IndexName, FullTypeName) /// /// Builds the full per-connection setup script (PRAGMAs + schema DDL) for the /// given performance profile, honoring optional cache-size / mmap overrides, and - /// shedding the indexes earlier versions created unless told not to. + /// shedding the indexes earlier versions created unless told not to. The pragma + /// that only applies to a database being created is included for a new file only. /// public static string BuildConnectionScript( TychoPerformanceProfile profile, int? cacheSizeKbOverride = null, long? mmapSizeBytesOverride = null, - bool dropLegacyIndexes = true) + bool dropLegacyIndexes = true, + bool newDatabase = true) { bool desktop = profile == TychoPerformanceProfile.Desktop; @@ -124,9 +131,14 @@ public static string BuildConnectionScript( int walAutocheckpoint = desktop ? DesktopWalAutocheckpoint : MobileWalAutocheckpoint; long journalSizeLimit = desktop ? DesktopJournalSizeLimitBytes : MobileJournalSizeLimitBytes; - var sb = new System.Text.StringBuilder(SharedPragmas.Length + SchemaDdl.Length + DropLegacyIndexes.Length + 160); + var sb = new System.Text.StringBuilder(CreationPragma.Length + SharedPragmas.Length + SchemaDdl.Length + DropLegacyIndexes.Length + 160); var ic = System.Globalization.CultureInfo.InvariantCulture; + if (newDatabase) + { + sb.Append(CreationPragma).Append('\n'); + } + sb.Append(SharedPragmas).Append('\n') .Append("PRAGMA cache_size = -").Append(cacheSizeKb.ToString(ic)).Append(";\n") .Append("PRAGMA mmap_size = ").Append(mmapSizeBytes.ToString(ic)).Append(";\n") diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index f4c87c2..4329226 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -42,8 +42,11 @@ private const string private readonly Lock _connectionLock = new(); private readonly string _dbConnectionString; - // Per-connection setup script (profile PRAGMAs + schema DDL), built once. + // Per-connection setup scripts (profile PRAGMAs + schema DDL), built once: one for + // opening an existing file and one, with the creation-only pragma, for a new one. private readonly string _connectionScript; + private readonly string _creationScript; + private readonly string _databasePath; private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; @@ -161,7 +164,9 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; - _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize); + _databasePath = databasePath; + _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: false); + _creationScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: true); } /// @@ -2978,7 +2983,7 @@ private SqliteConnection BuildConnection() connection .WithConnectionBlock( _connectionGate, - _connectionScript, + ConnectionScript(), static (conn, script) => { conn.Open(); @@ -3007,6 +3012,7 @@ private async ValueTask BuildConnectionAsync(CancellationToken try { + var script = ConnectionScript(); var connection = new SqliteConnection(_dbConnectionString); connection.Open(); @@ -3020,7 +3026,7 @@ private async ValueTask BuildConnectionAsync(CancellationToken // Profile PRAGMAs + idempotent schema/index creation. Composed from // library constants and numeric profile values only (no user input). #pragma warning disable CA2100 - command.CommandText = _connectionScript; + command.CommandText = script; #pragma warning restore CA2100 command.ExecuteNonQuery(); @@ -3033,6 +3039,17 @@ private async ValueTask BuildConnectionAsync(CancellationToken } } + /// + /// The setup script for the file as it is now: a new or empty file gets the + /// creation-only auto_vacuum pragma, an existing one is opened without it. + /// + private string ConnectionScript() + { + var file = new FileInfo(_databasePath); + + return file.Exists && file.Length > 0 ? _connectionScript : _creationScript; + } + // 0 = not yet verified this process, 1 = verified as supported. private static int _jsonSupportVerified; From 8d71dcbab23fcc6230b0dd620e8d6014e29b3ad7 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Wed, 14 Oct 2026 19:50:50 -0500 Subject: [PATCH 14/25] fix: delete leftover planner statistics at connect instead of dropping the table --- TychoDB.UnitTests/IndexDdlTests.cs | 9 +++--- TychoDB.UnitTests/PlannerStatisticsTests.cs | 5 ++- TychoDB/Queries.cs | 29 ++++++++++------- TychoDB/Tycho.cs | 36 +++++++++++++++++++++ 4 files changed, 63 insertions(+), 16 deletions(-) diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index f8354aa..3be1774 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -225,12 +225,13 @@ public async Task CreateIndex_GathersNoPlannerStatistics() await db.CreateIndexAsync(x => x.LongProperty, "long_idx"); } - // The planner runs on default heuristics, which favor the partial indexes; - // see PlannerStatisticsTests for why statistics would only mislead it. + // The planner runs on default heuristics, which favor the partial indexes; see + // PlannerStatisticsTests for why statistics would only mislead it. A store only + // TychoDB has written has no statistics table at all. using var conn = OpenInspection(Path.Combine(path, dbName)); using var command = conn.CreateCommand(); - command.CommandText = "SELECT COUNT(*) FROM sqlite_stat1"; - Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(0); + command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; + command.ExecuteScalar().ShouldBeNull(); } [TestMethod] diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 9aa95c3..874f613 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -287,7 +287,10 @@ private static string ReadPhysicalIndexName(string dbFile, string indexName) return (string)command.ExecuteScalar(); } - /// Every statistics row in the store; connecting leaves sqlite_stat1 behind, empty. + /// + /// Every statistics row in the store. A store that had statistics keeps sqlite_stat1, + /// empty, after connecting deletes its rows; one that never had any has no such table. + /// private static List ReadStatRows(string dbFile) { var rows = new List(); diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index e6fbd2a..13c4b03 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -68,17 +68,6 @@ CREATE TABLE IF NOT EXISTS TychoIndex ShapeVersion INTEGER NOT NULL, PRIMARY KEY (IndexName, FullTypeName) ); - - -- The planner chooses the right index for every query TychoDB emits on its - -- default heuristics, and statistics only mislead it: a sample of the - -- type-ordered general index credits every type with a handful of rows, and - -- the planner then reads every row of a type on each indexed lookup. Earlier - -- releases gathered them. Whatever an ANALYZE left behind is dropped, and the - -- reload makes this connection forget what it read at open; it leaves an empty - -- sqlite_stat1 behind. - DROP TABLE IF EXISTS sqlite_stat1; - DROP TABLE IF EXISTS sqlite_stat4; - ANALYZE sqlite_master; """; // Indexes earlier versions created that duplicate either the primary-key autoindex @@ -626,6 +615,24 @@ FROM TychoIndex public const string SelectPhysicalIndexExists = "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + // Planner statistics. TychoDB gathers none — SQLite's default heuristics choose the + // right index for every query it emits, and sampled statistics made the planner read + // every row of a type on each indexed lookup (5.3.0, 5.3.1) — and deletes what an + // earlier release or an external ANALYZE left, reloading so the open connection + // forgets them. Only the rows go: dropping the table is pointless, since ANALYZE + // sqlite_master recreates it, and a store with no rows is not written to. + public const string SelectStatisticsTableExists = + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1';"; + + public const string SelectStatisticsRowExists = + "SELECT 1 FROM sqlite_stat1 LIMIT 1;"; + + public const string DeleteStatistics = + """ + DELETE FROM sqlite_stat1; + ANALYZE sqlite_master; + """; + // Cache common LIMIT values using FrozenDictionary for O(1) lookup private static readonly FrozenDictionary CachedLimits = new Dictionary { diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 4329226..4e0c0a7 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -2657,9 +2657,41 @@ public ValueTask OptimizeAsync(CancellationToken cancellationToken = defau private static bool OptimizeStore(SqliteConnection conn) { ExecuteNonQuery(conn, Queries.DropLegacyIndexes); + RemoveLeftoverStatistics(conn); return true; } + /// + /// Deletes planner statistics an earlier release or an external ANALYZE left + /// in the file and reloads them on this connection. TychoDB gathers none: SQLite's + /// default heuristics choose the right index for every query it emits, and sampled + /// statistics made the planner read every row of a type on each indexed lookup + /// (5.3.0, 5.3.1). Writes nothing when there is nothing to delete, so a current + /// store's connect is read-only, and never drops the table: ANALYZE + /// sqlite_master would recreate it. + /// + private static void RemoveLeftoverStatistics(SqliteConnection conn) + { + if (ExecuteScalar(conn, Queries.SelectStatisticsTableExists) is null + || ExecuteScalar(conn, Queries.SelectStatisticsRowExists) is null) + { + return; + } + + ExecuteNonQuery(conn, Queries.DeleteStatistics); + } + + private static object? ExecuteScalar(SqliteConnection conn, string commandText) + { + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Library constants only. + command.CommandText = commandText; +#pragma warning restore CA2100 + + return command.ExecuteScalar(); + } + /// /// Performs database cleanup operations to optimize performance and reduce size. /// @@ -3000,6 +3032,8 @@ private SqliteConnection BuildConnection() #pragma warning restore CA2100 command.ExecuteNonQuery(); + + RemoveLeftoverStatistics(conn); }, _persistConnection); @@ -3031,6 +3065,8 @@ private async ValueTask BuildConnectionAsync(CancellationToken command.ExecuteNonQuery(); + RemoveLeftoverStatistics(connection); + return connection; } finally From a12be378f3ae98c2dfa29a6bc0fd19b2d7ed598b Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Wed, 14 Oct 2026 19:51:38 -0500 Subject: [PATCH 15/25] feat: defer index migrations under autoOptimize:false and widen Optimize --- TychoDB.UnitTests/OptimizeTests.cs | 576 +++++++++++++++++++++++++++++ TychoDB/Queries.cs | 48 +++ TychoDB/Tycho.cs | 448 ++++++++++++++++------ 3 files changed, 951 insertions(+), 121 deletions(-) create mode 100644 TychoDB.UnitTests/OptimizeTests.cs diff --git a/TychoDB.UnitTests/OptimizeTests.cs b/TychoDB.UnitTests/OptimizeTests.cs new file mode 100644 index 0000000..22e4229 --- /dev/null +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -0,0 +1,576 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; + +namespace TychoDB.UnitTests; + +/// +/// Proves the upgrade path a store takes from 4.x and the work Optimize does for it: +/// under autoOptimize: false a declaration whose index 4.x built is recorded as pending +/// and served by that index until Optimize rebuilds it; the string overload's +/// same-named 4.x index is recognised as stale instead of kept; the index a 4.x rollback +/// leaves next to a current one is dropped; and a current store is never written to by +/// connect, by a declaration, or by Optimize. +/// +[TestClass] +public class OptimizeTests +{ +#if ENCRYPTED + private const string DbPassword = "Password"; +#endif + + private const string IndexName = "seq_idx"; + private const string LegacyIndexName = "idx_seq_idx_Item"; + private const string ManualIndexName = "manual_idx"; + private const string ManualPhysicalName = "idx_manual_idx_Item"; + private const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; + + private const long LookupSeq = 42; + + private static readonly string[] BuiltInLegacyIndexNames = + { + "idx_jsonvalue_fulltypename", + "idx_jsonvalue_key_fulltypename", + "idx_jsonvalue_key_fulltypename_partition", + "idx_streamvalue_key_partition", + }; + + private static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); + + public class Item + { + public string Key { get; set; } + + public string Group { get; set; } + + public long Seq { get; set; } + } + + private readonly record struct MetadataRow( + string IndexName, + string FullTypeName, + string PhysicalName, + string Definition, + long ShapeVersion); + + [TestMethod] + public async Task LegacyStore_WithAutoOptimizeOff_DefersTheRebuildToOptimize() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + long schemaVersion = ReadPragma(dbFile, "schema_version"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + // Recorded as pending: no DDL ran, the 4.x index still serves the lookup. + var ddl = ReadIndexDdl(dbFile); + ddl[LegacyIndexName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + ddl.Keys.ShouldNotContain(k => k.StartsWith(LegacyIndexName + "_", StringComparison.Ordinal)); + ddl.Keys.ShouldContain("idx_jsonvalue_fulltypename"); + + var pending = ReadMetadata(dbFile).ShouldHaveSingleItem(); + pending.IndexName.ShouldBe(IndexName); + pending.FullTypeName.ShouldBe(typeof(Item).FullName); + pending.PhysicalName.ShouldStartWith(LegacyIndexName + "_"); + pending.Definition.ShouldContain("WHERE FullTypeName", Case.Sensitive); + pending.ShapeVersion.ShouldBe(0); + + var plan = ExplainLookup(dbFile); + plan.ShouldContain(LegacyIndexName, Case.Sensitive); + plan.ShouldNotContain(LegacyIndexName + "_", Case.Sensitive); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(0); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + await AssertLookup(db); + } + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[pending.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + ddl.ShouldContainKey(GeneralIndexName); + + foreach (var name in BuiltInLegacyIndexNames) + { + ddl.ShouldNotContainKey(name); + } + + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + ExplainLookup(dbFile).ShouldContain(pending.PhysicalName, Case.Sensitive); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + + // Done once: declaring and optimizing again touch nothing. + var hash = FileHash(dbFile); + schemaVersion = ReadPragma(dbFile, "schema_version"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + } + + FileHash(dbFile).ShouldBe(hash); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + } + + [TestMethod] + public async Task LegacyStore_WithAutoOptimizeOn_RebuildsOnDeclaration() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.ShapeVersion.ShouldBe(2); + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[row.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + + foreach (var name in BuiltInLegacyIndexNames) + { + ddl.ShouldNotContainKey(name); + } + + ExplainLookup(dbFile).ShouldContain(row.PhysicalName, Case.Sensitive); + } + + [TestMethod] + public async Task NewIndex_WithAutoOptimizeOff_IsBuiltAtOnce() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + } + + // Nothing in the schema serves the declaration, so deferring it would leave the + // lookup without an index. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.ShapeVersion.ShouldBe(2); + ReadIndexDdl(dbFile).ShouldContainKey(row.PhysicalName); + ExplainLookup(dbFile).ShouldContain(row.PhysicalName, Case.Sensitive); + } + + [TestMethod] + public async Task RolledBackStore_OrphanLegacyIndex_IsDropped() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var current = ReadMetadata(dbFile).ShouldHaveSingleItem(); + var currentSql = ReadIndexDdl(dbFile)[current.PhysicalName]; + + // 4.x reopened the store and built its own index for the same declaration. + Execute(dbFile, LegacyIndexDdl(LegacyIndexName)); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + + // Declared again with autoOptimize off: the orphan is left for Optimize. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + await AssertLookup(db); + } + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[current.PhysicalName].ShouldBe(currentSql); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(current); + + // Declared again with autoOptimize on: dropped on the spot. + Execute(dbFile, LegacyIndexDdl(LegacyIndexName)); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[current.PhysicalName].ShouldBe(currentSql); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(current); + } + + [TestMethod] + public async Task StringOverload_SameNamedLegacyIndex_IsRecognisedAsStale() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + } + + // 4.x built its index under the very name the string overload uses. + Execute(dbFile, LegacyIndexDdl(ManualPhysicalName)); + + // autoOptimize off: recorded as pending, the 4.x index left to serve queries. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", ManualIndexName); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + + var pending = ReadMetadata(dbFile).ShouldHaveSingleItem(); + pending.IndexName.ShouldBe(ManualIndexName); + pending.FullTypeName.ShouldBe("Item"); + pending.PhysicalName.ShouldBe(ManualPhysicalName); + pending.ShapeVersion.ShouldBe(0); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + + // Earlier 5.x releases recorded the declaration as current over the 4.x index, + // which CREATE INDEX IF NOT EXISTS had silently kept. autoOptimize on rebuilds it. + Execute(dbFile, $"DROP INDEX {ManualPhysicalName}; " + LegacyIndexDdl(ManualPhysicalName)); + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", ManualIndexName); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + + [TestMethod] + public async Task CurrentStore_ConnectDeclareAndOptimize_WriteNothing() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Group", isNumeric: false, "Item", ManualIndexName); + } + + var hash = FileHash(dbFile); + long schemaVersion = ReadPragma(dbFile, "schema_version"); + + foreach (var autoOptimize in new[] { true, false }) + { + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Group", isNumeric: false, "Item", ManualIndexName); + db.Optimize(); + await AssertLookup(db); + } + + FileHash(dbFile).ShouldBe(hash); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + } + } + + [TestMethod] + public async Task Connect_DeletesLeftoverStatisticsOnce_ThenLeavesTheEmptyTableAlone() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'sqlite_stat1'").ShouldBe(0); + + Execute(dbFile, "ANALYZE;"); + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBeGreaterThan(0); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(0); + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'sqlite_stat1'").ShouldBe(1); + + var hash = FileHash(dbFile); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + FileHash(dbFile).ShouldBe(hash); + } + + // ---------- seeding ---------- + + /// + /// A store as 4.4.2 leaves it: its per-type index for Seq under the legacy name and + /// shape, its four built-in indexes, no index metadata, and no incremental auto-vacuum. + /// + private static async Task SeedLegacyStore() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + } + + var legacySchema = + LegacyIndexDdl(LegacyIndexName) + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_fulltypename ON JsonValue (FullTypeName);" + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_key_fulltypename ON JsonValue (Key, FullTypeName);" + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_key_fulltypename_partition ON JsonValue (Key, FullTypeName, Partition);" + + "CREATE INDEX IF NOT EXISTS idx_streamvalue_key_partition ON StreamValue (Key, Partition);" + + "DELETE FROM TychoIndex;" + + "PRAGMA auto_vacuum = NONE; VACUUM;"; + + Execute(dbFile, legacySchema); + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(0); + ReadMetadata(dbFile).ShouldBeEmpty(); + + return dbFile; + } + + /// The DDL 4.4.2 ran for CreateIndex<Item>(x => x.Seq, …): whole-table, led by FullTypeName. + private static string LegacyIndexDdl(string name) + => $"CREATE INDEX IF NOT EXISTS {name} ON JsonValue(FullTypeName, CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC));"; + + private static List Items() + { + var items = new List(100); + for (int i = 0; i < 100; i++) + { + items.Add(new Item + { + Key = $"item-{i}", + Group = "G" + (i % 10).ToString(CultureInfo.InvariantCulture), + Seq = i, + }); + } + + return items; + } + + // ---------- assertions ---------- + private static async Task AssertLookup(Tycho db) + { + var rows = await db.ReadObjectsAsync( + filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Seq, LookupSeq)); + + rows.ShouldHaveSingleItem().Seq.ShouldBe(LookupSeq); + } + + /// The plan for the SQL the library composes for the lookup runs. + private static string ExplainLookup(string dbFile) + { + var sb = new StringBuilder(Queries.SelectDataFromJsonValueWithFullTypeName); + var parameters = new FilterParameters(); + FilterBuilder.Create().Filter(FilterType.Equals, x => x.Seq, LookupSeq).Build(sb, Serializer, parameters); + + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // SQL is produced by the library's own builders. + command.CommandText = "EXPLAIN QUERY PLAN " + sb; +#pragma warning restore CA2100 + + command.Parameters.AddWithValue("$fullTypeName", typeof(Item).FullName); + command.Parameters.AddWithValue("$partition", string.Empty); + for (int i = 0; i < parameters.Count; i++) + { + command.Parameters.AddWithValue( + FilterParameters.ParameterPrefix + i.ToString(CultureInfo.InvariantCulture), + parameters.Values[i] ?? (object)DBNull.Value); + } + + var plan = new StringBuilder(); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + plan.AppendLine(reader.GetString(reader.FieldCount - 1)); + } + + return plan.ToString(); + } + + // ---------- inspection ---------- + private static Dictionary ReadIndexDdl(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL"; + + var result = new Dictionary(StringComparer.Ordinal); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + result[reader.GetString(0)] = reader.GetString(1); + } + + return result; + } + + private static List ReadMetadata(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT IndexName, FullTypeName, PhysicalName, Definition, ShapeVersion FROM TychoIndex"; + + var rows = new List(); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + rows.Add(new MetadataRow(reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt64(4))); + } + + return rows; + } + + private static long ReadPragma(string dbFile, string pragma) + => ReadScalar(dbFile, "PRAGMA " + pragma); + + private static long ReadScalar(string dbFile, string sql) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Test-local SQL. + command.CommandText = sql; +#pragma warning restore CA2100 + + return command.ExecuteScalar() is long value ? value : -1; + } + + private static void Execute(string dbFile, string sql) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Test-local SQL. + command.CommandText = sql; +#pragma warning restore CA2100 + + command.ExecuteNonQuery(); + } + + /// The main file's bytes, once every pooled connection has closed and checkpointed. + private static string FileHash(string dbFile) + { + SqliteConnection.ClearAllPools(); + + using var stream = File.OpenRead(dbFile); + return Convert.ToHexString(SHA256.HashData(stream)); + } + + // ---------- plumbing ---------- + private static (string Path, string DbName) NewDbPath() + { + var dir = Path.Combine(Path.GetTempPath(), "tycho_optimize_tests"); + Directory.CreateDirectory(dir); + return (dir, $"{Guid.NewGuid()}.db"); + } + + private static (string Path, string DbName) Split(string dbFile) + => (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + private static Tycho BuildDb(string path, string dbName) + { +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: true, requireTypeRegistration: false); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: true, requireTypeRegistration: false); +#endif + } + + /// Reopens an existing database without rebuilding it. + private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = true) + { + SqliteConnection.ClearAllPools(); +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#endif + } + + /// + /// Opens an inspection connection carrying the same key the database was created with. + /// Tycho holds locking_mode = EXCLUSIVE and pooling keeps a disposed connection's lock + /// alive, so the pool must be cleared after the Tycho instance is disposed and before + /// the file is reopened. + /// + private static SqliteConnection OpenInspection(string dbFile) + { + SqliteConnection.ClearAllPools(); + + var connectionStringBuilder = + new SqliteConnectionStringBuilder + { + ConnectionString = $"Filename={dbFile}", + Cache = SqliteCacheMode.Private, + Mode = SqliteOpenMode.ReadWriteCreate, + }; + +#if ENCRYPTED + connectionStringBuilder.Password = DbPassword; +#endif + + var conn = new SqliteConnection(connectionStringBuilder.ToString()); + conn.Open(); + return conn; + } +} diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 13c4b03..4575b98 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -59,6 +59,9 @@ CREATE TABLE IF NOT EXISTS StreamValue PRIMARY KEY (Key, Partition) ); + -- ShapeVersion is the generated index shape the row was built in, or 0 for a + -- definition recorded under autoOptimize:false and not built yet (see + -- Tycho.PendingIndexShapeVersion). CREATE TABLE IF NOT EXISTS TychoIndex ( IndexName TEXT NOT NULL, @@ -615,6 +618,31 @@ FROM TychoIndex public const string SelectPhysicalIndexExists = "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + public const string SelectIndexSql = + "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + + public const string SelectIndexNames = + "SELECT name FROM sqlite_master WHERE type = 'index';"; + + /// + /// The text sqlite_master keeps for an index this class's DDL created: SQLite stores + /// "CREATE INDEX " and then the statement from the index name on, verbatim, so the + /// IF NOT EXISTS and the closing semicolon are not part of it. + /// + public static string StoredIndexSql(string createIndexStatement) + => string.Concat("CREATE INDEX ".AsSpan(), createIndexStatement.AsSpan(CreateIndexPrefix.Length).TrimEnd(';')); + + /// Whether is a statement this class built for the index named. + public static bool IsIndexDefinitionFor(string definition, string physicalName) + { + int nameEnd = CreateIndexPrefix.Length + physicalName.Length; + + return definition.Length > nameEnd + && definition.StartsWith(CreateIndexPrefix, StringComparison.Ordinal) + && string.CompareOrdinal(definition, CreateIndexPrefix.Length, physicalName, 0, physicalName.Length) == 0 + && definition[nameEnd] == '\n'; + } + // Planner statistics. TychoDB gathers none — SQLite's default heuristics choose the // right index for every query it emits, and sampled statistics made the planner read // every row of a type on each indexed lookup (5.3.0, 5.3.1) — and deletes what an @@ -633,6 +661,26 @@ FROM TychoIndex ANALYZE sqlite_master; """; + public const string ShrinkMemory = "PRAGMA shrink_memory;"; + + public const string AutoVacuumMode = "PRAGMA auto_vacuum;"; + + public const string FreelistCount = "PRAGMA freelist_count;"; + + public const string PageCount = "PRAGMA page_count;"; + + // In-place reclamation of free pages, then a WAL truncation so that space returns to + // disk too. Only effective in INCREMENTAL auto-vacuum mode. + public const string IncrementalVacuum = + "PRAGMA incremental_vacuum; PRAGMA wal_checkpoint(TRUNCATE);"; + + // A store without incremental auto-vacuum can only shrink through a full VACUUM, + // which also converts it. The rebuild uses a file-backed temp store so a large + // database does not spike memory (VACUUM would otherwise honor temp_store = MEMORY + // and build the whole copy in RAM); the in-memory temp store is restored afterwards. + public const string FullVacuum = + "PRAGMA temp_store = FILE; PRAGMA auto_vacuum = INCREMENTAL; VACUUM; PRAGMA temp_store = MEMORY; PRAGMA wal_checkpoint(TRUNCATE);"; + // Cache common LIMIT values using FrozenDictionary for O(1) lookup private static readonly FrozenDictionary CachedLimits = new Dictionary { diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 4e0c0a7..44cdbd9 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -36,6 +36,14 @@ private const string /// private const int IndexShapeVersion = 2; + /// + /// The ShapeVersion recorded for an index whose build was deferred: the definition is + /// the one will build, and the physical index it names is not + /// in the schema yet — whatever index the previous release built for the same + /// declaration still is, and serves queries meanwhile. + /// + private const int PendingIndexShapeVersion = 0; + // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); @@ -50,6 +58,7 @@ private const string private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; + private readonly bool _autoOptimize; // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -108,11 +117,14 @@ private const string /// Optional override for the SQLite page cache size, in KiB. Overrides the profile default. /// Optional override for the SQLite memory-map size, in bytes (0 disables mmap). Overrides the profile default. /// - /// Whether connecting drops the redundant indexes 4.x created. Freeing their pages - /// runs on the connecting thread and took 10–30 s on a large store upgraded from - /// 4.x; pass false to connect without it and call or - /// from a background thread at a convenient time, which - /// does the same work. Default is true. + /// Whether the one-time work an upgraded store needs runs inline: connecting drops the + /// four redundant indexes 4.x created, and CreateIndex rebuilds an index whose + /// stored shape is out of date. Both run on the calling thread and took seconds to + /// tens of seconds on a large store upgraded from 4.x. Pass false to skip both — + /// connect leaves the indexes in place, and CreateIndex records the wanted + /// definition as pending while queries keep using the index the previous release + /// built — and call or from a + /// background thread at a convenient time. Default is true. /// public Tycho( string dbPath, @@ -164,6 +176,7 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; + _autoOptimize = autoOptimize; _databasePath = databasePath; _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: false); _creationScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: true); @@ -2212,52 +2225,81 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) } /// - /// Creates an index if an identical one is not already recorded, migrating away - /// from any previous shape or name for the same logical index. + /// Brings the schema in line with one index declaration. + /// + /// Mobile apps declare their indexes on every launch, so the already-current case + /// must be cheap: one metadata lookup and two sqlite_master probes, no DDL. The probe + /// reads the physical index's stored DDL rather than its mere presence, so a + /// same-named index of another shape — the one 4.x built under the name the string + /// overload still uses, which CREATE INDEX IF NOT EXISTS would keep without a + /// word — counts as stale, and a stale index is rebuilt. + /// /// - /// Mobile apps typically call CreateIndex on every launch, so the already-current - /// case must be cheap: it costs one metadata lookup and one sqlite_master probe, - /// with no DDL. + /// With the rebuild happens here. Without it, when + /// an index the previous release built for the same declaration is still in the + /// schema, the wanted definition is recorded as pending and that index keeps serving + /// queries until replaces it; a declaration nothing in the + /// schema serves is built here either way, because no index is the slower outcome. /// /// - private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) + private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition, bool migrateInline) { using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); try { - if (IsIndexCurrent(conn, definition)) + var recorded = ReadRecordedIndex(conn, definition); + string? physicalSql = ReadIndexSql(conn, definition.PhysicalName); + bool hasLegacyName = !string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal); + bool legacyPresent = hasLegacyName + ? IndexExists(conn, definition.LegacyPhysicalName) + : physicalSql is not null; + + if (string.Equals(physicalSql, Queries.StoredIndexSql(definition.CommandText), StringComparison.Ordinal)) { + if (!IsRecordedAs(recorded, definition, IndexShapeVersion)) + { + UpsertIndexMetadata(conn, definition, IndexShapeVersion); + } + + if (hasLegacyName && legacyPresent && migrateInline) + { + ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + } + transaction.Commit(); return true; } - // Drop the previously recorded physical index (shape or definition - // changed) and any pre-metadata index that used the legacy name, so an - // upgraded database does not keep maintaining a stale b-tree forever. - foreach (var stalePhysicalName in ReadRecordedPhysicalNames(conn, definition)) + if (legacyPresent && !migrateInline) { - ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); + if (!IsRecordedAs(recorded, definition, PendingIndexShapeVersion)) + { + UpsertIndexMetadata(conn, definition, PendingIndexShapeVersion); + } + + transaction.Commit(); + return true; } - if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) + if (recorded is { } stale && !string.Equals(stale.PhysicalName, definition.PhysicalName, StringComparison.Ordinal)) { - ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stale.PhysicalName))); } - ExecuteNonQuery(conn, definition.CommandText); + if (physicalSql is not null) + { + ExecuteNonQuery(conn, Queries.DropIndex(definition.PhysicalName)); + } - using (var upsert = conn.CreateCommand()) + if (hasLegacyName && legacyPresent) { - upsert.CommandText = Queries.UpsertIndexMetadata; - upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); - upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); - upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); - upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definition.CommandText }); - upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = IndexShapeVersion }); - upsert.ExecuteNonQuery(); + ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); } + ExecuteNonQuery(conn, definition.CommandText); + UpsertIndexMetadata(conn, definition, IndexShapeVersion); + transaction.Commit(); } catch (Exception ex) @@ -2269,57 +2311,84 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de return true; } - /// - /// True when the recorded definition matches what would be created now and the - /// physical index is still present in the schema. - /// - private static bool IsIndexCurrent(SqliteConnection conn, IndexDefinition definition) + /// One row of the TychoIndex metadata table, as stored. + private readonly record struct IndexMetadataRow( + string IndexName, + string FullTypeName, + string PhysicalName, + string Definition, + long ShapeVersion); + + private static IndexMetadataRow? ReadRecordedIndex(SqliteConnection conn, IndexDefinition definition) { using var lookup = conn.CreateCommand(); lookup.CommandText = Queries.SelectIndexMetadata; lookup.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); lookup.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); - string? recordedDefinition = null; - long recordedVersion = -1; + using var reader = lookup.ExecuteReader(); + + return reader.Read() + ? new IndexMetadataRow(definition.IndexName, definition.MetadataTypeName, reader.GetString(0), reader.GetString(1), reader.GetInt64(2)) + : null; + } - using (var reader = lookup.ExecuteReader()) - { - if (reader.Read()) - { - recordedDefinition = reader.GetString(1); - recordedVersion = reader.GetInt64(2); - } - } + private static bool IsRecordedAs(IndexMetadataRow? recorded, IndexDefinition definition, int shapeVersion) + => recorded is { } row + && row.ShapeVersion == shapeVersion + && string.Equals(row.Definition, definition.CommandText, StringComparison.Ordinal); - if (recordedVersion != IndexShapeVersion || - !string.Equals(recordedDefinition, definition.CommandText, StringComparison.Ordinal)) - { - return false; - } + /// The stored DDL of the index named, or null when the schema has no such index. + private static string? ReadIndexSql(SqliteConnection conn, string physicalName) + { + using var lookup = conn.CreateCommand(); + lookup.CommandText = Queries.SelectIndexSql; + lookup.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); + return lookup.ExecuteScalar() as string; + } + private static bool IndexExists(SqliteConnection conn, string physicalName) + { using var exists = conn.CreateCommand(); exists.CommandText = Queries.SelectPhysicalIndexExists; - exists.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); + exists.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); return exists.ExecuteScalar() is not null; } - private static List ReadRecordedPhysicalNames(SqliteConnection conn, IndexDefinition definition) - { - var names = new List(1); + private static void UpsertIndexMetadata(SqliteConnection conn, IndexDefinition definition, int shapeVersion) + => UpsertIndexMetadata(conn, definition.IndexName, definition.MetadataTypeName, definition.PhysicalName, definition.CommandText, shapeVersion); - using var lookup = conn.CreateCommand(); - lookup.CommandText = Queries.SelectIndexMetadata; - lookup.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); - lookup.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); + private static void UpsertIndexMetadata( + SqliteConnection conn, + string indexName, + string typeName, + string physicalName, + string definitionText, + int shapeVersion) + { + using var upsert = conn.CreateCommand(); + upsert.CommandText = Queries.UpsertIndexMetadata; + upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = indexName }); + upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = typeName }); + upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); + upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definitionText }); + upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = shapeVersion }); + upsert.ExecuteNonQuery(); + } - using var reader = lookup.ExecuteReader(); - while (reader.Read()) - { - names.Add(reader.GetString(0)); - } + /// + /// The name the same declaration had before physical names carried a hash of the + /// type: the name 4.x built it under, and the string overload still does. Null when + /// the recorded name carries no hash of the recorded type — the string overload's + /// own rows, whose legacy name is their physical name. + /// + private static string? LegacyPhysicalNameOf(string physicalName, string fullTypeName) + { + string suffix = string.Concat("_", StableHashSuffix(fullTypeName)); - return names; + return physicalName.Length > suffix.Length && physicalName.EndsWith(suffix, StringComparison.Ordinal) + ? physicalName[..^suffix.Length] + : null; } private Tycho CreateIndexCore( @@ -2340,8 +2409,8 @@ private Tycho CreateIndexCore( _connection .WithConnectionBlock( _connectionGate, - definition, - static (conn, definition) => ExecuteCreateIndex(conn, definition), + (definition, migrateInline: _autoOptimize), + static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.migrateInline), _persistConnection); return this; @@ -2366,8 +2435,8 @@ private ValueTask CreateIndexCoreAsync( return _connection .WithConnectionBlockAsync( _connectionGate, - definition, - static (conn, definition) => ExecuteCreateIndex(conn, definition), + (definition, migrateInline: _autoOptimize), + static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.migrateInline), _persistConnection, cancellationToken); } @@ -2557,6 +2626,11 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(physicalName))); + if (LegacyPhysicalNameOf(physicalName, typeName) is { } legacyName) + { + ExecuteNonQuery(conn, Queries.DropIndex(legacyName)); + } + using (var delete = conn.CreateCommand()) { delete.CommandText = Queries.DeleteIndexMetadata; @@ -2576,8 +2650,10 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st } /// - /// Lists the indexes Tycho has created, as recorded in its metadata table. - /// Indexes created directly against the database outside Tycho are not listed. + /// Lists the indexes Tycho has created, as recorded in its metadata table. An index + /// declared under autoOptimize: false whose build has + /// not done yet is listed with the definition it will get. Indexes created directly + /// against the database outside Tycho are not listed. /// /// The recorded indexes, ordered by type then index name. public IReadOnlyList ListIndexes() @@ -2590,19 +2666,12 @@ public IReadOnlyList ListIndexes() null, static (conn, _) => { - var results = new List(); - - using var command = conn.CreateCommand(); - command.CommandText = Queries.SelectAllIndexMetadata; + var rows = ReadIndexMetadata(conn); + var results = new List(rows.Count); - using var reader = command.ExecuteReader(); - while (reader.Read()) + foreach (var row in rows) { - results.Add(new TychoIndexInfo( - reader.GetString(0), - reader.GetString(1), - reader.GetString(2), - reader.GetString(3))); + results.Add(new TychoIndexInfo(row.IndexName, row.FullTypeName, row.PhysicalName, row.Definition)); } return results; @@ -2610,17 +2679,63 @@ public IReadOnlyList ListIndexes() _persistConnection); } + private static List ReadIndexMetadata(SqliteConnection conn) + { + var rows = new List(); + + using var command = conn.CreateCommand(); + command.CommandText = Queries.SelectAllIndexMetadata; + + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + rows.Add(new IndexMetadataRow( + reader.GetString(0), + reader.GetString(1), + reader.GetString(2), + reader.GetString(3), + reader.GetInt64(4))); + } + + return rows; + } + + private static HashSet ReadIndexNames(SqliteConnection conn) + { + var names = new HashSet(StringComparer.Ordinal); + + using var command = conn.CreateCommand(); + command.CommandText = Queries.SelectIndexNames; + + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + names.Add(reader.GetString(0)); + } + + return names; + } + /// - /// Does what connecting does on its own when autoOptimize is on: drops the - /// redundant indexes 4.x created. A no-op once they are gone, so calling it on + /// Does the one-time work an upgraded store needs, in one hold of the connection: + /// drops the four redundant indexes 4.x created; builds every index + /// CreateIndex recorded as pending under autoOptimize: false and drops + /// the index the previous release built for it; drops the per-type indexes a 4.x + /// rollback recreated next to their replacements; deletes planner statistics an + /// external ANALYZE left; and returns the pages all of that freed to the file + /// system — through a full VACUUM when the store was created without + /// incremental auto-vacuum (every 4.x store), which also converts it, or an in-place + /// incremental_vacuum when at least a tenth of the file is free. Idempotent: + /// with nothing pending it reads the schema and writes nothing, so calling it on /// every launch is fine. /// /// Holds the database's single connection for the duration, so every other - /// operation on this instance waits: freeing the indexes' pages took 10–30 s on a - /// large store upgraded from 4.x. The work runs on the calling thread — - /// Microsoft.Data.Sqlite executes synchronously, so - /// does not move it off the caller by itself — and must not be called from a UI - /// thread. + /// operation on this instance waits: on a 3 GB store upgraded from 4.x the drops, + /// the rebuilds and the VACUUM took about 5, 6 and 24 s, and the + /// VACUUM needs free disk space for a copy of the file. The work runs on the + /// calling thread — Microsoft.Data.Sqlite executes synchronously, so + /// does not move it off the caller by itself — and must + /// not be called from a UI thread. /// /// public void Optimize() @@ -2656,11 +2771,95 @@ public ValueTask OptimizeAsync(CancellationToken cancellationToken = defau private static bool OptimizeStore(SqliteConnection conn) { - ExecuteNonQuery(conn, Queries.DropLegacyIndexes); - RemoveLeftoverStatistics(conn); + try + { + ExecuteNonQuery(conn, Queries.DropLegacyIndexes); + RebuildPendingIndexes(conn); + RemoveLeftoverStatistics(conn); + ReclaimFreeSpace(conn); + } + catch (Exception ex) when (ex is not TychoException) + { + throw new TychoException("Failed to optimize database", ex); + } + return true; } + /// + /// Builds each index recorded as pending in a transaction of its own, dropping the + /// index the previous release built for it, so an interruption leaves that index + /// either as it was or complete; and drops the legacy-named index a 4.x rollback + /// recreated next to a current one. A legacy name another row records as its own + /// index is left alone. + /// + private static void RebuildPendingIndexes(SqliteConnection conn) + { + var rows = ReadIndexMetadata(conn); + + if (rows.Count == 0) + { + return; + } + + var indexNames = ReadIndexNames(conn); + var recordedNames = new HashSet(StringComparer.Ordinal); + + foreach (var row in rows) + { + recordedNames.Add(row.PhysicalName); + } + + foreach (var row in rows) + { + string physicalName = ValidateStoredIndexName(row.PhysicalName); + string? legacyName = LegacyPhysicalNameOf(physicalName, row.FullTypeName); + string? orphanName = legacyName is not null && indexNames.Contains(legacyName) && !recordedNames.Contains(legacyName) + ? legacyName + : null; + + if (row.ShapeVersion == IndexShapeVersion) + { + if (orphanName is not null) + { + ExecuteNonQuery(conn, Queries.DropIndex(orphanName)); + } + + continue; + } + + if (!Queries.IsIndexDefinitionFor(row.Definition, physicalName)) + { + throw new TychoException($"Index metadata for {row.IndexName} does not define {physicalName}"); + } + + using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); + + try + { + if (orphanName is not null) + { + ExecuteNonQuery(conn, Queries.DropIndex(orphanName)); + } + + if (indexNames.Contains(physicalName)) + { + ExecuteNonQuery(conn, Queries.DropIndex(physicalName)); + } + + ExecuteNonQuery(conn, row.Definition); + UpsertIndexMetadata(conn, row.IndexName, row.FullTypeName, physicalName, row.Definition, IndexShapeVersion); + + transaction.Commit(); + } + catch (Exception ex) + { + transaction.Rollback(); + throw new TychoException($"Failed to Create Index: {physicalName}", ex); + } + } + } + /// /// Deletes planner statistics an earlier release or an external ANALYZE left /// in the file and reloads them on this connection. TychoDB gathers none: SQLite's @@ -2681,6 +2880,37 @@ private static void RemoveLeftoverStatistics(SqliteConnection conn) ExecuteNonQuery(conn, Queries.DeleteStatistics); } + /// + /// Returns freed pages to the file system. A store created without incremental + /// auto-vacuum — every 4.x store: its connect script set the pragma after + /// journal_mode = WAL, which fixed the mode at NONE — can only shrink through + /// a full VACUUM, which rewrites the file and converts it, so later calls take + /// the in-place path; that path runs when at least a tenth of the file is free, so a + /// store with a little churn is left alone. + /// + private static void ReclaimFreeSpace(SqliteConnection conn) + { + long autoVacuumMode = ReadPragma(conn, Queries.AutoVacuumMode); + + if (autoVacuumMode == 0) + { + ExecuteNonQuery(conn, Queries.FullVacuum); + return; + } + + if (autoVacuumMode != 2) + { + return; + } + + long freePages = ReadPragma(conn, Queries.FreelistCount); + + if (freePages > 0 && freePages * 10 >= ReadPragma(conn, Queries.PageCount)) + { + ExecuteNonQuery(conn, Queries.IncrementalVacuum); + } + } + private static object? ExecuteScalar(SqliteConnection conn, string commandText) { using var command = conn.CreateCommand(); @@ -2692,6 +2922,9 @@ private static void RemoveLeftoverStatistics(SqliteConnection conn) return command.ExecuteScalar(); } + private static long ReadPragma(SqliteConnection conn, string pragma) + => ExecuteScalar(conn, pragma) is long value ? value : 0L; + /// /// Performs database cleanup operations to optimize performance and reduce size. /// @@ -2718,9 +2951,7 @@ public void Cleanup(bool shrinkMemory = true, bool vacuum = false) { if (state.shrinkMemory) { - using var shrinkCommand = conn.CreateCommand(); - shrinkCommand.CommandText = "PRAGMA shrink_memory;"; - shrinkCommand.ExecuteNonQuery(); + ExecuteNonQuery(conn, Queries.ShrinkMemory); } if (!state.vacuum) @@ -2729,36 +2960,11 @@ public void Cleanup(bool shrinkMemory = true, bool vacuum = false) } // incremental_vacuum only reclaims space when the database is in - // INCREMENTAL (2) auto-vacuum mode. - long autoVacuumMode; - using (var modeCommand = conn.CreateCommand()) - { - modeCommand.CommandText = "PRAGMA auto_vacuum;"; - autoVacuumMode = modeCommand.ExecuteScalar() is long mode ? mode : 0L; - } - - using var vacuumCommand = conn.CreateCommand(); - - if (autoVacuumMode == 2) - { - // In-place free-page reclamation, then truncate the WAL file so - // its space is returned to disk too. - vacuumCommand.CommandText = - "PRAGMA incremental_vacuum; PRAGMA wal_checkpoint(TRUNCATE);"; - } - else - { - // Legacy/NONE database: a full VACUUM reclaims free space and - // converts to incremental auto-vacuum. Use a file-backed temp - // store for the rebuild so a large database does not spike - // memory (VACUUM would otherwise honor temp_store = MEMORY and - // build the whole copy in RAM), then restore the in-memory - // temp store for normal operation and truncate the WAL. - vacuumCommand.CommandText = - "PRAGMA temp_store = FILE; PRAGMA auto_vacuum = INCREMENTAL; VACUUM; PRAGMA temp_store = MEMORY; PRAGMA wal_checkpoint(TRUNCATE);"; - } - - vacuumCommand.ExecuteNonQuery(); + // INCREMENTAL (2) auto-vacuum mode; a legacy/NONE database needs + // the full VACUUM, which also converts it. + ExecuteNonQuery( + conn, + ReadPragma(conn, Queries.AutoVacuumMode) == 2 ? Queries.IncrementalVacuum : Queries.FullVacuum); } catch (Exception ex) { From 6a33cc04cd570608d5c1269d67ffb5008ad1a61f Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Wed, 14 Oct 2026 19:51:55 -0500 Subject: [PATCH 16/25] docs: describe the 5.4.0 upgrade path, Optimize and the statistics removal --- CHANGELOG.md | 70 ++++++++++++++++++++++------- README.md | 47 ++++++++++++------- docs/indexing-analysis.md | 5 +++ docs/planner-statistics-sampling.md | 50 ++++++++++++++------- 4 files changed, 123 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0918b0..e3c52f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 5.3.2 (unreleased) +## 5.4.0 (unreleased) ### Fixed @@ -17,25 +17,63 @@ throughout; only speed changed. TychoDB no longer gathers statistics at all: SQLite's default heuristics choose the right index for every query shape it emits (equality, range, sort with a limit, two indexed filters, an unindexed filter, a whole type, a - count — verified on both bundled engines), while keeping statistics correct would have - cost a full `ANALYZE` of 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store, plus - a way to tell when they had gone stale. Connect drops the statistics tables an earlier - release left behind and reloads, so an upgraded store is repaired on its first connect - whether or not `autoOptimize` is on; an empty `sqlite_stat1` remains. + count — verified on both bundled engines, and on a 1.8M-row, 3 GB production store the + plans and timings with and without statistics were identical), while keeping statistics + correct would have cost a full `ANALYZE` of 3.2 s on the 1.68M-row store and 17.5 s on a + 2.2 GB store, plus a way to tell when they had gone stale. Connect and `Optimize()` + delete the `sqlite_stat1` rows an earlier release or an external `ANALYZE` left and + reload, so an upgraded store is repaired on its first connect whether or not + `autoOptimize` is on; nothing is written when there are no rows, and the table is never + dropped, since `ANALYZE sqlite_master` would recreate it. The one thing statistics could + add — ranking two single-property indexes when a filter ANDs both — is what a composite + index is for. +- **The string overload of `CreateIndex` silently kept the index 4.x built.** It names its + index exactly as 4.x did, so its `CREATE INDEX IF NOT EXISTS` met the 4.x index and did + nothing, while the metadata recorded the new definition as built: queries still matched + the old `(FullTypeName, expr)` shape, but the index carried every type's rows and the + metadata lied for good. `CreateIndex` now compares the stored DDL of a same-named index + with the definition it wants and rebuilds on a mismatch — on the spot, or through + `Optimize()` under `autoOptimize: false` — which also repairs the stores earlier 5.x + releases recorded that way. +- **A 4.x rollback left its per-type indexes behind for good.** After 5.x → 4.x → 5.x, + 4.x had recreated `idx__` next to the 5.x `idx___`, and the + re-declaration found its own index current and never looked at the legacy name, so both + were maintained on every write and the planner could prefer the wider one. `CreateIndex` + now probes the legacy name on the current path and drops it (left to `Optimize()` under + `autoOptimize: false`), `Optimize()` sweeps it for every recorded index, and `DropIndex` + drops it together with the index. +- **Connecting to an existing store wrote page 1 every time.** `PRAGMA auto_vacuum = + INCREMENTAL` only takes effect on a database being created, but on an auto-vacuum store + it stores the mode the file already has, in a write transaction that bumps the change + counter. It now runs only for a new or empty file, so connecting to a current store + writes nothing: the file is byte-identical afterwards. ### Added - **`autoOptimize` constructor parameter (default `true`), `Optimize()` and - `OptimizeAsync()`.** Connecting a store written by 4.x drops the four redundant indexes - it created — most of a 10–30 s first launch measured on a large upgraded store, since - freeing an index's pages takes time proportional to its size and SQLCipher's default - `secure_delete` writes every freed page back. Pass `autoOptimize: false` to connect - without the drops and call `Optimize()` or `OptimizeAsync()` when convenient — on a - loading page, for example; they are a no-op once the indexes are gone. They hold the - single connection for the duration, so every other operation on the instance waits, and - run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so - `OptimizeAsync` alone does not move the work off the caller — so call them from a - background thread. + `OptimizeAsync()`.** A store written by 4.x needs one-time work that runs on the calling + thread: connecting drops the four redundant indexes 4.x created — most of a 10–30 s first + launch measured on a large upgraded store, since freeing an index's pages takes time + proportional to its size and SQLCipher's default `secure_delete` writes every freed page + back — and the first `CreateIndex` for each declaration drops the whole-table index 4.x + built for it and builds the partial one (0.5–2.2 s each on a 1.8M-row store). Pass + `autoOptimize: false` to defer both: connect leaves the indexes in place, and + `CreateIndex` records the declaration as pending (`ShapeVersion 0` in `TychoIndex`) + while queries keep using the index 4.x built; a declaration no existing index serves is + built at once either way. `Optimize()` / `OptimizeAsync()` then do, in one hold of the + connection: the four drops, every pending rebuild (each in a transaction of its own, so + an interruption leaves either the old index or the new one), the orphan drops a rollback + needs, the statistics delete, and a full `VACUUM` when the store has no incremental + auto-vacuum — every 4.x store, whose connect script set the pragma too late — which + returns the freed pages to the file system (3.06 GB → 1.08 GB in 24 s on the production + store) and converts the store, or an in-place `incremental_vacuum` when at least a tenth + of the file is free. Idempotent: with nothing pending they read the schema and write + nothing, so calling them on every launch is fine. They hold the single connection for + the duration, so every other operation on the instance waits, and run on the calling + thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not + move the work off the caller — so call them from a background thread; the `VACUUM` needs + free disk space for a copy of the file. `ListIndexes()` lists a pending index with the + definition it will get. ## 5.3.1 — 2026-10-05 diff --git a/README.md b/README.md index 07bb264..36a472a 100644 --- a/README.md +++ b/README.md @@ -492,20 +492,32 @@ This matters for how they behave: a numeric property is `CAST(... as NUMERIC)` everywhere, a non-numeric property is plain `JSON_EXTRACT` everywhere. - **Calling `CreateIndex` repeatedly is cheap and safe.** Definitions are recorded in a - `TychoIndex` metadata table; re-declaring an unchanged index is a metadata lookup with - no DDL. Declaring the same index name with a *different* property rebuilds it and drops - the old one, and indexes created by older versions are migrated away automatically. - Declaring your indexes on every app launch is the intended usage. + `TychoIndex` metadata table; re-declaring an unchanged index is a metadata lookup and + two schema probes with no DDL. Declaring the same index name with a *different* + property rebuilds it and drops the old one, and indexes created by older versions are + migrated away automatically — on the spot, or by `Optimize()` when the store was opened + with `autoOptimize: false` (see below). Declaring your indexes on every app launch is + the intended usage. - **No planner statistics.** TychoDB never runs `ANALYZE`. SQLite's default heuristics choose the right index for every query shape TychoDB emits, and statistics only made that choice worse: a sample of the type-ordered general index credits every type with a handful of rows, and the planner then reads every row of the type on each indexed lookup (5.3.0 and 5.3.1). Statistics an earlier release or an external `ANALYZE` left - in the file are removed at connect. -- **Dropping the indexes 4.x created** happens at connect and can stall the first launch - of a large upgraded store for 10–30 s; pass `autoOptimize: false` to skip it and call - `Optimize()` / `OptimizeAsync()` from a background thread instead — the same work, a - no-op once the indexes are gone. + in the file are deleted at connect and by `Optimize()`; a store without any is not + written to. +- **Filter on two properties? Declare a composite index.** Without statistics the planner + cannot rank two single-property indexes against each other, so a filter that ANDs two + indexed properties uses one of them and checks the other row by row; a composite index + on both serves it directly. +- **Upgrading a store from 4.x costs seconds to tens of seconds, once:** connecting drops + the four redundant indexes 4.x created, and the first `CreateIndex` for each + declaration drops the whole-table index 4.x built for it and builds the partial one. + Both run on the calling thread. Pass `autoOptimize: false` to defer both: connect leaves + the indexes in place, `CreateIndex` records each declaration as pending while queries + keep using the index 4.x built, and `Optimize()` / `OptimizeAsync()` — called from a + background thread — do the drops, the rebuilds, and a `VACUUM` that returns the freed + pages (about 2 GB on a 3 GB store) to the file system. A declaration no existing index + serves is built at once either way. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). @@ -550,11 +562,13 @@ db.Disconnect(); // Or disconnect asynchronously await db.DisconnectAsync(); -// Open without dropping the indexes 4.x created (freeing their pages can stall the first -// launch of a large upgraded store for 10–30 s) and do it later, from a background -// thread — on a loading page, for example +// Open without the one-time upgrade work (dropping the indexes 4.x created and rebuilding +// the per-type ones can stall the first launch of a large upgraded store for tens of +// seconds): connect and declare the indexes as usual, then do the work later, from a +// background thread — on a loading page, for example var deferredDb = new Tycho(dbPath: "./data", jsonSerializer: serializer, autoOptimize: false); await deferredDb.ConnectAsync(); +deferredDb.CreateIndex(x => x.Age, "age_index"); await Task.Run(() => deferredDb.Optimize()); ``` @@ -609,10 +623,11 @@ await db.DeleteObjectsAsync(); // Optimize database performance and reduce size db.Cleanup(shrinkMemory: true, vacuum: true); -// Drop the indexes 4.x created; a no-op once they are gone. Holds the connection for the -// duration — every other operation on this instance waits; 10–30 s on a large store -// upgraded from 4.x — and runs on the calling thread, so call it from a background -// thread, never the UI thread. +// Do the one-time work an upgraded store needs: drop the indexes 4.x created, build the +// indexes declared under autoOptimize: false, drop what a 4.x rollback left behind, and +// VACUUM. A no-op once done. Holds the connection for the duration — every other +// operation on this instance waits; about 35 s on a 3 GB store upgraded from 4.x — and +// runs on the calling thread, so call it from a background thread, never the UI thread. await Task.Run(() => db.Optimize()); ``` diff --git a/docs/indexing-analysis.md b/docs/indexing-analysis.md index deebbb7..5505baa 100644 --- a/docs/indexing-analysis.md +++ b/docs/indexing-analysis.md @@ -124,6 +124,11 @@ win; the query-plan sweep in that bucket must confirm no query regresses to a ta ## 5. Statistics +> **5.4.0:** the bounded `ANALYZE` and `PRAGMA optimize` this section led to sampled the +> indexes and misled the planner; TychoDB gathers no statistics now. See +> `docs/planner-statistics-sampling.md` for the regression and the design that replaced +> them. + `sqlite_stat1` does not exist even after a full connect→index-create→dispose cycle — `Disconnect`'s `PRAGMA optimize` produced no statistics table in the diagnose run. All plans above are chosen by default heuristics. Bucket 3 adds a bounded `ANALYZE` after diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index 87260f3..43cc240 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -36,11 +36,13 @@ every row of the type on each lookup. ## Fix -TychoDB gathers no statistics, and removes any it finds. The connect script ends with -`DROP TABLE IF EXISTS sqlite_stat1; DROP TABLE IF EXISTS sqlite_stat4; ANALYZE sqlite_master;` -— the last statement is SQLite's documented way to reload statistics on an open connection, -and it leaves an empty `sqlite_stat1` behind. Nothing else runs `ANALYZE` or -`PRAGMA optimize`. The one-time index drops stay, behind `autoOptimize` and `Optimize`. +TychoDB gathers no statistics, and removes any it finds. Connect and `Optimize()` look for +`sqlite_stat1`; when it exists and has rows they run `DELETE FROM sqlite_stat1; ANALYZE +sqlite_master;` — the last statement is SQLite's documented way to reload statistics on an +open connection — and otherwise write nothing. The table is never dropped: `ANALYZE +sqlite_master` recreates it, so dropping it only guarantees a schema write on the next +connect. Nothing else runs `ANALYZE` or `PRAGMA optimize`. The one-time index drops and +rebuilds stay, behind `autoOptimize` and `Optimize`. Without a `sqlite_stat1` row, SQLite's planner credits a partial index with half the table and every index with a fixed selectivity per equality column, so the per-type partial index @@ -63,7 +65,7 @@ The one thing statistics could add is the choice between two indexed properties together: without them the planner cannot tell which is more selective and picks one by rule, so the lookup is bounded by the rows matching that property rather than the smaller set. On the stores measured so far every indexed property is selective enough for this not -to matter. +to matter, and a query that filters on two properties is what a composite index is for. ## Why not gather them properly instead @@ -108,6 +110,13 @@ statistics, and that finding is reversed. sampled rows repaired on connect with `autoOptimize` on and off, and one test per query shape in the table above. Each asserts the plan for the library's own SQL and that no statistics row exists. +- `TychoDB.UnitTests/OptimizeTests.cs` — the upgrade path from 4.4.2 through Tycho's own + API: a store with 4.4.2's per-type and built-in indexes and no incremental auto-vacuum, + declared under `autoOptimize: false` (pending, served by the 4.4.2 index) and then + optimized (rebuilt, drops done, `VACUUM` run, store converted, nothing written on the + next launch); the same store under `autoOptimize: true`; the string overload's + same-named 4.4.2 index; the orphan a rollback leaves; and a current store that connect, + the declarations and `Optimize` leave byte-identical. Bound parameters are fine in the library: SQLite re-plans when a bound value touches a partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic @@ -115,28 +124,35 @@ plan. The tests bind the parameters; the CLI script uses literals. ## Cost -Connect pays two `DROP TABLE IF EXISTS` (a schema lookup each when there is nothing to -drop) and a statistics reload (a pass over the indexes in the schema). A store written by -5.3.0 or 5.3.1 pays the drop of its small statistics table once. +Connect pays one `sqlite_master` lookup for `sqlite_stat1`, and one `SELECT … LIMIT 1` on +it when the table exists. A store written by 5.3.0 or 5.3.1 pays the delete of its small +statistics table once; a current store is not written to at all (the connect script's +`auto_vacuum` pragma, which rewrote page 1 at every connect on an auto-vacuum store, now +runs only for a new file). The four `DROP INDEX IF EXISTS` for the indexes 4.x created were most of a 10–30 s stall MoveScoutPro measured on the first launch of a large upgraded store (main-thread samples in `sqlite3BtreeDropTable`/`clearDatabasePage`): freeing an index's pages is proportional to its size, and with `secure_delete` on — SQLCipher's default — every freed page is written back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6–7 ms each -plain and 39–54 ms each with `secure_delete`. They stay on by default, because they make -bulk writes 25–45% faster; `autoOptimize: false` connects without them and -`Optimize`/`OptimizeAsync` run them later. Both hold the single connection for the +plain and 39–54 ms each with `secure_delete`; on a 1.8M-row, 3 GB production store the +four took 5 s, and the six per-type rebuilds `CreateIndex` does for an upgraded store — +drop the whole-table index 4.x built, build the partial one — 6 s more. They stay on by +default, because they make bulk writes 25–45% faster. `autoOptimize: false` connects +without the drops and records each `CreateIndex` whose index 4.x built as pending, leaving +that index to serve queries; `Optimize`/`OptimizeAsync` then do the drops, the rebuilds, +the orphan sweep a 4.x rollback needs, the statistics delete, and a full `VACUUM` that +returns the freed pages — 1.9 GB on that store, in 24 s — since a 4.x store has no +incremental auto-vacuum and nothing else can. Both hold the single connection for the duration and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so the async form alone does not move the work off the caller — so apps call them from a -background thread. `CreateIndex` itself drops a per-type legacy index and builds the -partial one, which is the other piece of an upgrade stall and already under the app's -control through when it calls it. +background thread. ## Verification - Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and Encrypted (3.39.2). The two scenario tests fail on it in both configurations with `SEARCH JsonValue USING INDEX idx_jsonvalue_fulltypename_partition`. -- Final state: 373 passed, 4 skipped, 0 failed in both configurations (Debug 3 s, - Encrypted 1 m 24 s). +- Final state: 381 passed, 4 skipped, 0 failed in both configurations (Debug 2 s, + Encrypted 1 m 30 s), the eight new tests in `OptimizeTests.cs` and + `ConfigurationTests.cs` included. From 1c149c453baa1e84785c358ced2294e5a0f3ba8a Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Wed, 14 Oct 2026 20:38:21 -0500 Subject: [PATCH 17/25] docs: cite the upgrade timings measured through the library on the 1.8M-row store --- CHANGELOG.md | 25 +++++++++------- README.md | 21 +++++++------- TychoDB/Tycho.cs | 6 ++-- docs/planner-statistics-sampling.md | 45 ++++++++++++++++++++++++----- 4 files changed, 65 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3c52f7..0b0a00b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,21 +52,24 @@ - **`autoOptimize` constructor parameter (default `true`), `Optimize()` and `OptimizeAsync()`.** A store written by 4.x needs one-time work that runs on the calling - thread: connecting drops the four redundant indexes 4.x created — most of a 10–30 s first - launch measured on a large upgraded store, since freeing an index's pages takes time - proportional to its size and SQLCipher's default `secure_delete` writes every freed page - back — and the first `CreateIndex` for each declaration drops the whole-table index 4.x - built for it and builds the partial one (0.5–2.2 s each on a 1.8M-row store). Pass - `autoOptimize: false` to defer both: connect leaves the indexes in place, and - `CreateIndex` records the declaration as pending (`ShapeVersion 0` in `TychoIndex`) - while queries keep using the index 4.x built; a declaration no existing index serves is - built at once either way. `Optimize()` / `OptimizeAsync()` then do, in one hold of the + thread: connecting drops the four redundant indexes 4.x created — 9 s on a 1.8M-row, + 3 GB store, and most of a 10–30 s first launch measured in an app on device, since + freeing an index's pages takes time proportional to its size and SQLCipher's default + `secure_delete` writes every freed page back — and the first `CreateIndex` for each + declaration drops the whole-table index 4.x built for it and builds the partial one + (0.7–4.7 s each on that store, 9 s for six). Pass `autoOptimize: false` to defer both: + connect leaves the indexes in place, and `CreateIndex` records the declaration as + pending (`ShapeVersion 0` in `TychoIndex`) while queries keep using the index 4.x built + — connect and six declarations then take about 140 ms on that store; a declaration no + existing index serves is built at once either way. `Optimize()` / `OptimizeAsync()` + then do, in one hold of the connection: the four drops, every pending rebuild (each in a transaction of its own, so an interruption leaves either the old index or the new one), the orphan drops a rollback needs, the statistics delete, and a full `VACUUM` when the store has no incremental auto-vacuum — every 4.x store, whose connect script set the pragma too late — which - returns the freed pages to the file system (3.06 GB → 1.08 GB in 24 s on the production - store) and converts the store, or an in-place `incremental_vacuum` when at least a tenth + returns the freed pages to the file system (3.06 GB → 1.03 GB in 5 s on that store; the + whole call took 26 s) and converts the store, or an in-place `incremental_vacuum` when + at least a tenth of the file is free. Idempotent: with nothing pending they read the schema and write nothing, so calling them on every launch is fine. They hold the single connection for the duration, so every other operation on the instance waits, and run on the calling diff --git a/README.md b/README.md index 36a472a..283b314 100644 --- a/README.md +++ b/README.md @@ -509,15 +509,16 @@ This matters for how they behave: cannot rank two single-property indexes against each other, so a filter that ANDs two indexed properties uses one of them and checks the other row by row; a composite index on both serves it directly. -- **Upgrading a store from 4.x costs seconds to tens of seconds, once:** connecting drops - the four redundant indexes 4.x created, and the first `CreateIndex` for each - declaration drops the whole-table index 4.x built for it and builds the partial one. - Both run on the calling thread. Pass `autoOptimize: false` to defer both: connect leaves - the indexes in place, `CreateIndex` records each declaration as pending while queries - keep using the index 4.x built, and `Optimize()` / `OptimizeAsync()` — called from a - background thread — do the drops, the rebuilds, and a `VACUUM` that returns the freed - pages (about 2 GB on a 3 GB store) to the file system. A declaration no existing index - serves is built at once either way. +- **Upgrading a store from 4.x costs tens of seconds, once:** connecting drops the four + redundant indexes 4.x created (9 s on a 1.8M-row, 3 GB store), and the first + `CreateIndex` for each declaration drops the whole-table index 4.x built for it and + builds the partial one (9 s for six). Both run on the calling thread. Pass + `autoOptimize: false` to defer both: connect and the declarations then cost about + 140 ms, `CreateIndex` records each declaration as pending while queries keep using the + index 4.x built, and `Optimize()` / `OptimizeAsync()` — called from a background + thread — do the drops, the rebuilds, and a `VACUUM` that returns the freed pages to the + file system (3.06 GB to 1.03 GB in 5 s; 26 s for the whole call). A declaration no + existing index serves is built at once either way. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). @@ -626,7 +627,7 @@ db.Cleanup(shrinkMemory: true, vacuum: true); // Do the one-time work an upgraded store needs: drop the indexes 4.x created, build the // indexes declared under autoOptimize: false, drop what a 4.x rollback left behind, and // VACUUM. A no-op once done. Holds the connection for the duration — every other -// operation on this instance waits; about 35 s on a 3 GB store upgraded from 4.x — and +// operation on this instance waits; 26 s on a 1.8M-row, 3 GB store upgraded from 4.x — and // runs on the calling thread, so call it from a background thread, never the UI thread. await Task.Run(() => db.Optimize()); ``` diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 44cdbd9..932ee1a 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -2730,9 +2730,9 @@ private static HashSet ReadIndexNames(SqliteConnection conn) /// every launch is fine. /// /// Holds the database's single connection for the duration, so every other - /// operation on this instance waits: on a 3 GB store upgraded from 4.x the drops, - /// the rebuilds and the VACUUM took about 5, 6 and 24 s, and the - /// VACUUM needs free disk space for a copy of the file. The work runs on the + /// operation on this instance waits: on a 1.8M-row, 3 GB store upgraded from 4.x the + /// drops, the rebuilds and the VACUUM took about 9, 9 and 5 s, 26 s in all, and + /// the VACUUM needs free disk space for a copy of the file. The work runs on the /// calling thread — Microsoft.Data.Sqlite executes synchronously, so /// does not move it off the caller by itself — and must /// not be called from a UI thread. diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index 43cc240..a08d5a4 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -136,18 +136,47 @@ MoveScoutPro measured on the first launch of a large upgraded store (main-thread its size, and with `secure_delete` on — SQLCipher's default — every freed page is written back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6–7 ms each plain and 39–54 ms each with `secure_delete`; on a 1.8M-row, 3 GB production store the -four took 5 s, and the six per-type rebuilds `CreateIndex` does for an upgraded store — -drop the whole-table index 4.x built, build the partial one — 6 s more. They stay on by -default, because they make bulk writes 25–45% faster. `autoOptimize: false` connects -without the drops and records each `CreateIndex` whose index 4.x built as pending, leaving -that index to serve queries; `Optimize`/`OptimizeAsync` then do the drops, the rebuilds, -the orphan sweep a 4.x rollback needs, the statistics delete, and a full `VACUUM` that -returns the freed pages — 1.9 GB on that store, in 24 s — since a 4.x store has no -incremental auto-vacuum and nothing else can. Both hold the single connection for the +four took 9 s through the library, and the six per-type rebuilds `CreateIndex` does for an +upgraded store — drop the whole-table index 4.x built, build the partial one — 9 s more +(0.7–4.7 s each). They stay on by default, because they make bulk writes 25–45% faster. +`autoOptimize: false` connects without the drops and records each `CreateIndex` whose +index 4.x built as pending, leaving that index to serve queries — about 140 ms for the +connect and six declarations on that store; `Optimize`/`OptimizeAsync` then do the drops, +the rebuilds, the orphan sweep a 4.x rollback needs, the statistics delete, and a full +`VACUUM` that returns the freed pages — 2 GB on that store, in 5 s; 26 s for the whole +call — since a 4.x store has no incremental auto-vacuum and nothing else can. The numbers +are in the table below. Both hold the single connection for the duration and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so the async form alone does not move the work off the caller — so apps call them from a background thread. +## Measured on the real store + +Through the library on a copy of a 4.4.2 production store (1,801,125 rows, 3,063 MB, eleven +indexes, no `TychoIndex`, `auto_vacuum` NONE), Release build, e_sqlite3 3.50.3, NVMe, the +file just copied so everything is warm. The lookups are the app's four: a pricing level by +brand, origin and load date; a distance by SPLC pair; a zip3; a zip. + +| `autoOptimize: false` | Time | +|---|---| +| Connect | 72 ms | +| Six `CreateIndex`, all recorded pending, no DDL | 69 ms (67 of it the first call's JIT) | +| Lookups while pending, on the 4.4.2 indexes | pricing 5.3 ms, SPLC 0.2 ms, zip3 and zip 0.05 ms | +| `Optimize()`: four drops, six rebuilds, `VACUUM`, conversion | 26.3 s | +| Lookups after | pricing 0.64 ms, the others 0.05 ms | +| File | 3,063 MB → 1,030 MB, `auto_vacuum` 2, freelist 0 | +| Next launch: Connect, six `CreateIndex`, `Optimize()` | 44 ms, 34 ms, 1 ms | + +| `autoOptimize: true` | Time | +|---|---| +| Connect, the four drops | 9.2 s | +| Six `CreateIndex` inline, drop the 4.4.2 index and build | 9.0 s (0.7–4.7 s each) | +| File after launch | 2,922 MB, 476,124 free pages, still NONE | +| `Optimize()` on the next launch, the `VACUUM` alone | 5.4 s → 1,030 MB; a further call 1 ms | + +The string overload's same-named 4.4.2 index on a 5,000-row store: 4 ms to detect the +mismatch and record it pending, 15 ms for `Optimize()` to rebuild it, 9 ms inline. + ## Verification - Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and From e19ae953b8e1876eb92902e48bf53fa47eca0baf Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Thu, 15 Oct 2026 00:12:21 -0500 Subject: [PATCH 18/25] docs: add the bulk-write and cold-cache figures measured on the 1.8M-row store --- CHANGELOG.md | 22 ++++++++++++---------- README.md | 5 +++++ docs/planner-statistics-sampling.md | 26 +++++++++++++++++++++++++- 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b0a00b..6985185 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,16 +62,18 @@ pending (`ShapeVersion 0` in `TychoIndex`) while queries keep using the index 4.x built — connect and six declarations then take about 140 ms on that store; a declaration no existing index serves is built at once either way. `Optimize()` / `OptimizeAsync()` - then do, in one hold of the - connection: the four drops, every pending rebuild (each in a transaction of its own, so - an interruption leaves either the old index or the new one), the orphan drops a rollback - needs, the statistics delete, and a full `VACUUM` when the store has no incremental - auto-vacuum — every 4.x store, whose connect script set the pragma too late — which - returns the freed pages to the file system (3.06 GB → 1.03 GB in 5 s on that store; the - whole call took 26 s) and converts the store, or an in-place `incremental_vacuum` when - at least a tenth - of the file is free. Idempotent: with nothing pending they read the schema and write - nothing, so calling them on every launch is fine. They hold the single connection for + then do, in one hold of the connection: the four drops, every pending rebuild (each in a + transaction of its own, so an interruption leaves either the old index or the new one), + the orphan drops a rollback needs, the statistics delete, and a full `VACUUM` when the + store has no incremental auto-vacuum — every 4.x store, whose connect script set the + pragma too late — which returns the freed pages to the file system (3.06 GB → 1.03 GB in + 5 s on that store; the whole call took 26 s) and converts the store, or an in-place + `incremental_vacuum` when at least a tenth of the file is free. None of these timings + changed with the file cold on disk. With the whole-table 4.x indexes gone, 50,000-row + bulk writes on that store ran 2.1x faster for an indexed type (38k → 80k rows/s) and 3x + for an unindexed one (62k → 190k rows/s), and partition deletes 2.2–2.7x. Idempotent: + with nothing pending they read the schema and write nothing, so calling them on every + launch is fine. They hold the single connection for the duration, so every other operation on the instance waits, and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not move the work off the caller — so call them from a background thread; the `VACUUM` needs diff --git a/README.md b/README.md index 283b314..49eba41 100644 --- a/README.md +++ b/README.md @@ -519,6 +519,11 @@ This matters for how they behave: thread — do the drops, the rebuilds, and a `VACUUM` that returns the freed pages to the file system (3.06 GB to 1.03 GB in 5 s; 26 s for the whole call). A declaration no existing index serves is built at once either way. +- **The upgrade pays back on every write.** With the whole-table 4.x indexes gone, + 50,000-row bulk writes on that store ran 2.1x faster for an indexed type (38k to 80k + rows/s) and 3x for an unindexed one (62k to 190k rows/s), and partition deletes 2.2x to + 2.7x. The timings above were the same with the file cold on disk: nothing in the + upgrade or the launch path is bound by random reads any more. Index names are scoped per type, so the same name can be reused for different types (including two types that share a short name in different namespaces). diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index a08d5a4..ea645c8 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -138,7 +138,9 @@ back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6 plain and 39–54 ms each with `secure_delete`; on a 1.8M-row, 3 GB production store the four took 9 s through the library, and the six per-type rebuilds `CreateIndex` does for an upgraded store — drop the whole-table index 4.x built, build the partial one — 9 s more -(0.7–4.7 s each). They stay on by default, because they make bulk writes 25–45% faster. +(0.7–4.7 s each). They stay on by default, because they make bulk writes faster: 25–45% +measured for 5.0 with the four built-ins alone, 2.1–3x on the production store once the +six whole-table per-type indexes go too (table below). `autoOptimize: false` connects without the drops and records each `CreateIndex` whose index 4.x built as pending, leaving that index to serve queries — about 140 ms for the connect and six declarations on that store; `Optimize`/`OptimizeAsync` then do the drops, @@ -177,6 +179,28 @@ brand, origin and load date; a distance by SPLC pair; a zip3; a zip. The string overload's same-named 4.4.2 index on a 5,000-row store: 4 ms to detect the mismatch and record it pending, 15 ms for `Optimize()` to rebuild it, 9 ms inline. +Cold: the same runs with the file copied without caching (`F_NOCACHE`; a system purge +needs root), verified cold by a first sequential read at half the cached speed. Every phase +was within noise of the warm run — deferred connect 78 ms and declarations 62 ms, first +lookups 113 / 8.4 / 1.9 / 1.1 ms, `Optimize()` 23.8 s, inline connect 9.3 s and +declarations 9.6 s, the steady-state launch on the cold 1 GB file 44 / 37 / 1 ms with first +lookups 34 / 7.3 / 1.5 / 1.4 ms. Nothing left on the login path scales with random reads; +the 457 s cold `ANALYZE` of the statistics design was that. + +Bulk writes on the same store, warm, 50,000 rows per `WriteObjectsAsync` into a fresh +partition and `DeleteObjectsAsync` of that partition, steady-state repetitions: + +| | 4.4.2 shape, 11 indexes | Upgraded, 7 indexes | Gain | +|---|---|---|---| +| Write `PricingLevelModel` (three indexes on the type) | 37,700–38,000 rows/s | 78,200–82,900 rows/s | 2.1x | +| Write `DeltaDownloadDateModel` (no index on the type) | 59,000–65,600 rows/s | 184,000–194,000 rows/s | 3.0x | +| Delete the partition, indexed type | 1.0 s | 0.47 s | 2.2x | +| Delete the partition, unindexed type | 0.68 s | 0.25 s | 2.7x | + +The 25–45% measured for 5.0 covered the four built-in drops on a synthetic store; the six +whole-table per-type indexes 4.4.2 built cost as much again, and a partial index costs +nothing for the types it does not cover. + ## Verification - Baseline, unmodified 5.3.1: 362 passed, 4 skipped, in both Debug (SQLite 3.50.4) and From 53c7f84fb917697a0e1785c4f3900bb0c1b238e0 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Tue, 20 Oct 2026 12:11:18 -0500 Subject: [PATCH 19/25] fix: keep a legacy-named index that another declaration records as its own --- TychoDB.UnitTests/OptimizeTests.cs | 65 +++++++++++++++++++++++++++++- TychoDB/Queries.cs | 8 ++++ TychoDB/Tycho.cs | 29 +++++++++++-- 3 files changed, 97 insertions(+), 5 deletions(-) diff --git a/TychoDB.UnitTests/OptimizeTests.cs b/TychoDB.UnitTests/OptimizeTests.cs index 22e4229..1247e3e 100644 --- a/TychoDB.UnitTests/OptimizeTests.cs +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -18,8 +18,9 @@ namespace TychoDB.UnitTests; /// under autoOptimize: false a declaration whose index 4.x built is recorded as pending /// and served by that index until Optimize rebuilds it; the string overload's /// same-named 4.x index is recognised as stale instead of kept; the index a 4.x rollback -/// leaves next to a current one is dropped; and a current store is never written to by -/// connect, by a declaration, or by Optimize. +/// leaves next to a current one is dropped, while one another declaration records as its +/// own is kept; and a current store is never written to by connect, by a declaration, or +/// by Optimize. /// [TestClass] public class OptimizeTests @@ -352,6 +353,66 @@ public async Task Connect_DeletesLeftoverStatisticsOnce_ThenLeavesTheEmptyTableA FileHash(dbFile).ShouldBe(hash); } + [TestMethod] + public async Task BothOverloads_UnderOneName_LeaveEachOthersIndexAlone() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + // The string overload names its index exactly as 4.x did: the generic overload's + // legacy name. Declared second, the generic index must not take it for an orphan. + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", IndexName); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var rows = ReadMetadata(dbFile); + rows.Count.ShouldBe(2); + rows.ShouldAllBe(r => r.ShapeVersion == 2); + + var manual = rows.Single(r => r.PhysicalName == LegacyIndexName); + var generic = rows.Single(r => r.PhysicalName != LegacyIndexName); + manual.FullTypeName.ShouldBe("Item"); + generic.FullTypeName.ShouldBe(typeof(Item).FullName); + generic.PhysicalName.ShouldStartWith(LegacyIndexName + "_"); + + var ddl = ReadIndexDdl(dbFile); + ddl[LegacyIndexName].ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + ddl[generic.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + + // Every later launch finds both current and touches nothing, in either order. + var hash = FileHash(dbFile); + long schemaVersion = ReadPragma(dbFile, "schema_version"); + + foreach (var autoOptimize in new[] { true, false }) + { + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", IndexName); + db.Optimize(); + await AssertLookup(db); + } + + FileHash(dbFile).ShouldBe(hash); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + } + + // Dropping the generic declaration leaves the string overload's index and row. + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + db.DropIndex(IndexName).ShouldBeTrue(); + await AssertLookup(db); + } + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldContainKey(LegacyIndexName); + ddl.ShouldNotContainKey(generic.PhysicalName); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(manual); + } + // ---------- seeding ---------- /// diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 4575b98..771bdff 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -618,6 +618,14 @@ FROM TychoIndex public const string SelectPhysicalIndexExists = "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + public const string SelectIndexRecordedByAnother = + """ + SELECT 1 + FROM TychoIndex + WHERE PhysicalName = $physicalName + AND NOT (IndexName = $indexName AND FullTypeName = $fullTypeName); + """; + public const string SelectIndexSql = "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 932ee1a..f8144cf 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -2241,6 +2241,12 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) /// queries until replaces it; a declaration nothing in the /// schema serves is built here either way, because no index is the slower outcome. /// + /// + /// The index under the legacy name goes once the current one serves — unless another + /// TychoIndex row records that name as its own index, as the string overload's does + /// when an app declares one name through both overloads; that index is left alone, + /// as and leave it. + /// /// private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition, bool migrateInline) { @@ -2254,6 +2260,8 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de bool legacyPresent = hasLegacyName ? IndexExists(conn, definition.LegacyPhysicalName) : physicalSql is not null; + bool legacyOrphan = hasLegacyName && legacyPresent + && !IsRecordedByAnotherIndex(conn, definition.LegacyPhysicalName, definition.IndexName, definition.MetadataTypeName); if (string.Equals(physicalSql, Queries.StoredIndexSql(definition.CommandText), StringComparison.Ordinal)) { @@ -2262,7 +2270,7 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de UpsertIndexMetadata(conn, definition, IndexShapeVersion); } - if (hasLegacyName && legacyPresent && migrateInline) + if (legacyOrphan && migrateInline) { ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); } @@ -2292,7 +2300,7 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de ExecuteNonQuery(conn, Queries.DropIndex(definition.PhysicalName)); } - if (hasLegacyName && legacyPresent) + if (legacyOrphan) { ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); } @@ -2355,6 +2363,20 @@ private static bool IndexExists(SqliteConnection conn, string physicalName) return exists.ExecuteScalar() is not null; } + /// + /// Whether a TychoIndex row other than the one identified records + /// as its own index. + /// + private static bool IsRecordedByAnotherIndex(SqliteConnection conn, string physicalName, string indexName, string fullTypeName) + { + using var lookup = conn.CreateCommand(); + lookup.CommandText = Queries.SelectIndexRecordedByAnother; + lookup.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); + lookup.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = indexName }); + lookup.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = fullTypeName }); + return lookup.ExecuteScalar() is not null; + } + private static void UpsertIndexMetadata(SqliteConnection conn, IndexDefinition definition, int shapeVersion) => UpsertIndexMetadata(conn, definition.IndexName, definition.MetadataTypeName, definition.PhysicalName, definition.CommandText, shapeVersion); @@ -2626,7 +2648,8 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(physicalName))); - if (LegacyPhysicalNameOf(physicalName, typeName) is { } legacyName) + if (LegacyPhysicalNameOf(physicalName, typeName) is { } legacyName + && !IsRecordedByAnotherIndex(conn, legacyName, indexName, typeName)) { ExecuteNonQuery(conn, Queries.DropIndex(legacyName)); } From 6063b04b81145396b000677f072c38b8d47ce116 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Tue, 20 Oct 2026 12:11:26 -0500 Subject: [PATCH 20/25] fix: run a pending index definition only if it rebuilds byte for byte --- TychoDB.UnitTests/IndexDdlTests.cs | 26 ++++++++ TychoDB.UnitTests/OptimizeTests.cs | 70 +++++++++++++++++++- TychoDB/Queries.cs | 102 +++++++++++++++++++++++++++-- TychoDB/QueryPropertyPath.cs | 27 +++++++- 4 files changed, 216 insertions(+), 9 deletions(-) diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 3be1774..0b9a531 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -687,6 +687,32 @@ public async Task DroppedIndex_CanBeRecreated() /// Physical index names carry a hash suffix of the full type name, so tests /// locate an index by its logical name prefix rather than an exact key. /// + [TestMethod] + public void IndexDefinition_IsAcceptedOnlyAsBuilt() + { + const string name = "idx_seq_idx_Item_0a1b2c3d"; + var paths = new[] { ("$.Seq", true), ("$.Nested.Name", false), ("$.Tags[0]", false) }; + + var partial = Queries.CreateIndexForJsonValue(name, paths, typeof(IndexTestModel).FullName); + var quoted = Queries.CreateIndexForJsonValue(name, paths, "Ns.O'Brien+Item"); + var manual = Queries.CreateIndexForJsonValue(name, paths); + + Queries.IsIndexDefinitionFor(partial, name).ShouldBeTrue(); + Queries.IsIndexDefinitionFor(quoted, name).ShouldBeTrue(); + Queries.IsIndexDefinitionFor(manual, name).ShouldBeTrue(); + + Queries.IsIndexDefinitionFor(partial, "idx_seq_idx_Item").ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial + " DROP TABLE StreamValue;", name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.TrimEnd(';'), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(manual + " DROP TABLE StreamValue;", name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(manual.Replace(");", "); DROP TABLE StreamValue; --", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("WHERE FullTypeName = '", "WHERE FullTypeName = ''; DROP TABLE StreamValue; --", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("$.Seq", "$.Seq') as NUMERIC)); DROP TABLE StreamValue; --", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("JsonValue(", "StreamValue(", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("JSON_EXTRACT(Data, '$.Nested.Name')", "lower(JSON_EXTRACT(Data, '$.Nested.Name'))", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor($"CREATE INDEX IF NOT EXISTS {name}\nON JsonValue(Partition)\nWHERE FullTypeName = 'X';", name).ShouldBeFalse(); + } + private static string Find(Dictionary ddl, string logicalIndexName) { var prefix = $"idx_{logicalIndexName}_"; diff --git a/TychoDB.UnitTests/OptimizeTests.cs b/TychoDB.UnitTests/OptimizeTests.cs index 1247e3e..2104b9c 100644 --- a/TychoDB.UnitTests/OptimizeTests.cs +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -19,8 +19,9 @@ namespace TychoDB.UnitTests; /// and served by that index until Optimize rebuilds it; the string overload's /// same-named 4.x index is recognised as stale instead of kept; the index a 4.x rollback /// leaves next to a current one is dropped, while one another declaration records as its -/// own is kept; and a current store is never written to by connect, by a declaration, or -/// by Optimize. +/// own is kept; a current store is never written to by connect, by a declaration, or by +/// Optimize; and a pending definition that is not the statement Tycho built is +/// refused rather than run. /// [TestClass] public class OptimizeTests @@ -413,6 +414,61 @@ public async Task BothOverloads_UnderOneName_LeaveEachOthersIndexAlone() ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(manual); } + [TestMethod] + public async Task Optimize_RefusesATamperedPendingDefinition() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var pending = ReadMetadata(dbFile).ShouldHaveSingleItem(); + pending.ShapeVersion.ShouldBe(0); + + // Each keeps the prefix and the name Tycho wrote and carries a second statement: + // after the column list, and inside the type literal of the WHERE clause. + var tampered = new[] + { + $"CREATE INDEX IF NOT EXISTS {pending.PhysicalName}\nON JsonValue(Partition); DROP TABLE StreamValue; --", + pending.Definition.Replace("WHERE FullTypeName = '", "WHERE FullTypeName = ''; DROP TABLE StreamValue; --", StringComparison.Ordinal), + }; + + foreach (var definition in tampered) + { + definition.ShouldContain("DROP TABLE", Case.Sensitive); + WriteDefinition(dbFile, definition); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + Should.Throw(() => db.Optimize()).Message.ShouldContain(IndexName, Case.Sensitive); + await AssertLookup(db); + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'StreamValue'").ShouldBe(1); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + ReadIndexDdl(dbFile).ShouldNotContainKey(pending.PhysicalName); + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.ShapeVersion.ShouldBe(0); + row.Definition.ShouldBe(definition); + } + + // The definition as Tycho wrote it is built. + WriteDefinition(dbFile, pending.Definition); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile).ShouldContainKey(pending.PhysicalName); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + // ---------- seeding ---------- /// @@ -568,6 +624,16 @@ private static void Execute(string dbFile, string sql) command.ExecuteNonQuery(); } + /// Overwrites the one recorded index's definition, as a tampered file would carry it. + private static void WriteDefinition(string dbFile, string definition) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "UPDATE TychoIndex SET Definition = $definition"; + command.Parameters.AddWithValue("$definition", definition); + command.ExecuteNonQuery().ShouldBe(1); + } + /// The main file's bytes, once every pooled connection has closed and checkpointed. private static string FileHash(string dbFile) { diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 771bdff..70d8bb2 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -640,15 +640,105 @@ FROM TychoIndex public static string StoredIndexSql(string createIndexStatement) => string.Concat("CREATE INDEX ".AsSpan(), createIndexStatement.AsSpan(CreateIndexPrefix.Length).TrimEnd(';')); - /// Whether is a statement this class built for the index named. + /// + /// Whether is, byte for byte, a statement + /// + /// builds for the index named. The text is taken apart into the paths and the type it + /// indexes, each path is checked as a declaration's is, and the statement is built + /// again from them and compared. The value is read back out of the TychoIndex table + /// and executed as it stands, so it is re-checked rather than trusted: anything added + /// to it — a second statement, an expression this class never emits — does not survive + /// the round trip. + /// public static bool IsIndexDefinitionFor(string definition, string physicalName) + => TryParseIndexDefinition(definition, physicalName, out var propertyPaths, out var fullTypeName) + && string.Equals(definition, CreateIndexForJsonValue(physicalName, propertyPaths, fullTypeName), StringComparison.Ordinal); + + private static bool TryParseIndexDefinition( + string definition, + string physicalName, + out (string PropertyPathString, bool IsNumeric)[] propertyPaths, + out string? fullTypeName) + { + propertyPaths = Array.Empty<(string PropertyPathString, bool IsNumeric)>(); + fullTypeName = null; + + var rest = definition.AsSpan(); + + if (!Consume(ref rest, CreateIndexPrefix) || !Consume(ref rest, physicalName)) + { + return false; + } + + bool partial = Consume(ref rest, PartialIndexOnJsonValue); + + if (!partial && !(Consume(ref rest, MultiIndexOnJsonValue) && Consume(ref rest, PartitionColumnSegment))) + { + return false; + } + + var paths = new List<(string PropertyPathString, bool IsNumeric)>(); + + while (true) + { + bool numeric = Consume(ref rest, MultiIndexCastPrefix); + + if (!numeric && !Consume(ref rest, MultiIndexJsonExtractPrefix)) + { + break; + } + + int pathEnd = rest.IndexOf('\''); + + if (pathEnd < 0) + { + return false; + } + + string path = rest[..pathEnd].ToString(); + rest = rest[pathEnd..]; + + if (!QueryPropertyPath.IsValidPath(path) + || !Consume(ref rest, numeric ? MultiIndexCastSuffix : MultiIndexJsonExtractSuffix)) + { + return false; + } + + paths.Add((path, numeric)); + } + + if (paths.Count == 0) + { + return false; + } + + propertyPaths = paths.ToArray(); + + if (!partial) + { + return rest.SequenceEqual(MultiIndexClose.AsSpan()); + } + + if (!Consume(ref rest, ")") + || !Consume(ref rest, PartialIndexWherePrefix) + || !rest.EndsWith(PartialIndexWhereSuffix.AsSpan(), StringComparison.Ordinal)) + { + return false; + } + + fullTypeName = rest[..^PartialIndexWhereSuffix.Length].ToString().Replace("''", "'", StringComparison.Ordinal); + return true; + } + + private static bool Consume(ref ReadOnlySpan text, string token) { - int nameEnd = CreateIndexPrefix.Length + physicalName.Length; + if (!text.StartsWith(token.AsSpan(), StringComparison.Ordinal)) + { + return false; + } - return definition.Length > nameEnd - && definition.StartsWith(CreateIndexPrefix, StringComparison.Ordinal) - && string.CompareOrdinal(definition, CreateIndexPrefix.Length, physicalName, 0, physicalName.Length) == 0 - && definition[nameEnd] == '\n'; + text = text[token.Length..]; + return true; } // Planner statistics. TychoDB gathers none — SQLite's default heuristics choose the diff --git a/TychoDB/QueryPropertyPath.cs b/TychoDB/QueryPropertyPath.cs index 048c247..a1d27d1 100644 --- a/TychoDB/QueryPropertyPath.cs +++ b/TychoDB/QueryPropertyPath.cs @@ -249,7 +249,7 @@ public static void ValidatePath(string path, string paramName) foreach (var c in path) { - if (!(char.IsLetterOrDigit(c) || c is '$' or '.' or '_' or '[' or ']')) + if (!IsPathChar(c)) { throw new ArgumentException( $"Property path contains an invalid character '{c}'. Only letters, digits, '_', '.', '$', '[' and ']' are permitted.", @@ -258,6 +258,31 @@ public static void ValidatePath(string path, string paramName) } } + /// + /// Whether would pass : the check for + /// a path read back out of the database rather than supplied by a caller. + /// + public static bool IsValidPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + foreach (var c in path) + { + if (!IsPathChar(c)) + { + return false; + } + } + + return true; + } + + private static bool IsPathChar(char c) + => char.IsLetterOrDigit(c) || c is '$' or '.' or '_' or '[' or ']'; + /// /// Validates a caller-supplied SQL identifier (e.g. an index name). Identifiers /// are concatenated into DDL and cannot be parameterized, so they are limited From 05c29e5242c2b25a7fc1034644d571b40c1c895e Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Tue, 20 Oct 2026 12:11:45 -0500 Subject: [PATCH 21/25] fix: compact a store with VACUUM INTO and a file swap instead of a full VACUUM --- TychoDB.UnitTests/OptimizeTests.cs | 93 ++++++- TychoDB/Queries.cs | 34 ++- TychoDB/Tycho.cs | 389 +++++++++++++++++++++-------- 3 files changed, 409 insertions(+), 107 deletions(-) diff --git a/TychoDB.UnitTests/OptimizeTests.cs b/TychoDB.UnitTests/OptimizeTests.cs index 2104b9c..064e8ab 100644 --- a/TychoDB.UnitTests/OptimizeTests.cs +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -321,6 +321,81 @@ public async Task CurrentStore_ConnectDeclareAndOptimize_WriteNothing() } } + [TestMethod] + public async Task LegacyStore_Optimize_SwapsInTheCompactedCopy_AndKeepsServingOnIt() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + var compactedFile = dbFile + Queries.CompactedFileSuffix; + + // A copy an interrupted run left behind is replaced, not reused. + File.WriteAllText(compactedFile, "not a database"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + + // The instance works on the swapped-in file without reconnecting: the + // lookup, a write, and a read of that write all go through it. + await AssertLookup(db); + await db.WriteObjectAsync(new Item { Key = "item-new", Group = "G0", Seq = 1000 }, x => x.Key); + (await db.ReadObjectAsync("item-new")).ShouldNotBeNull().Seq.ShouldBe(1000); + (await db.CountObjectsAsync()).ShouldBe(101); + } + + File.Exists(compactedFile).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + ReadText(dbFile, "PRAGMA journal_mode").ShouldBe("wal"); + ReadScalar(dbFile, "SELECT COUNT(*) FROM JsonValue").ShouldBe(101); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + + // Reopened from scratch, the store is the compacted one. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(101); + } + } + + [TestMethod] + public async Task LegacyStore_Optimize_WithoutAPersistentConnection_Compacts() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false, persistConnection: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(100); + } + + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + + [TestMethod] + public async Task LegacyStore_Cleanup_CompactsThroughTheSameSwap() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Cleanup(shrinkMemory: true, vacuum: true); + (await db.CountObjectsAsync()).ShouldBe(100); + } + + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadText(dbFile, "PRAGMA journal_mode").ShouldBe("wal"); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + } + [TestMethod] public async Task Connect_DeletesLeftoverStatisticsOnce_ThenLeavesTheEmptyTableAlone() { @@ -612,6 +687,18 @@ private static long ReadScalar(string dbFile, string sql) return command.ExecuteScalar() is long value ? value : -1; } + private static string ReadText(string dbFile, string sql) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Test-local SQL. + command.CommandText = sql; +#pragma warning restore CA2100 + + return command.ExecuteScalar() as string ?? string.Empty; + } + private static void Execute(string dbFile, string sql) { using var conn = OpenInspection(dbFile); @@ -664,13 +751,13 @@ private static Tycho BuildDb(string path, string dbName) } /// Reopens an existing database without rebuilding it. - private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = true) + private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = true, bool persistConnection = true) { SqliteConnection.ClearAllPools(); #if ENCRYPTED - return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); + return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); #else - return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); + return new Tycho(path, Serializer, dbName, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); #endif } diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 70d8bb2..342452f 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -767,17 +767,39 @@ private static bool Consume(ref ReadOnlySpan text, string token) public const string PageCount = "PRAGMA page_count;"; + public const string PageSize = "PRAGMA page_size;"; + // In-place reclamation of free pages, then a WAL truncation so that space returns to // disk too. Only effective in INCREMENTAL auto-vacuum mode. public const string IncrementalVacuum = "PRAGMA incremental_vacuum; PRAGMA wal_checkpoint(TRUNCATE);"; - // A store without incremental auto-vacuum can only shrink through a full VACUUM, - // which also converts it. The rebuild uses a file-backed temp store so a large - // database does not spike memory (VACUUM would otherwise honor temp_store = MEMORY - // and build the whole copy in RAM); the in-memory temp store is restored afterwards. - public const string FullVacuum = - "PRAGMA temp_store = FILE; PRAGMA auto_vacuum = INCREMENTAL; VACUUM; PRAGMA temp_store = MEMORY; PRAGMA wal_checkpoint(TRUNCATE);"; + // A store without incremental auto-vacuum can only be converted by rewriting it. + // VACUUM INTO writes the live pages, once, into a new file next to the database, in + // the mode the pragma sets first — no temp copy, nothing back through the WAL — so + // the free space it needs is the compacted size, and the database is untouched until + // Tycho.CompactStore renames the copy over it. + public const string SetIncrementalAutoVacuum = "PRAGMA auto_vacuum = INCREMENTAL;"; + + public const string VacuumInto = "VACUUM INTO $path;"; + + public const string CompactedFileSuffix = "-compact"; + + // SQLCipher turns secure_delete on, and with it every page a DROP INDEX frees is + // zeroed through the WAL first, so the drops need free space equal to the index. + // Pointless when the whole file is about to be rewritten, so Optimize turns it off + // for its drops when a compaction follows and restores the mode it found. + public const string SecureDelete = "PRAGMA secure_delete;"; + + public const string SecureDeleteOff = "PRAGMA secure_delete = OFF;"; + + public static string RestoreSecureDelete(long mode) + => mode switch + { + 1 => "PRAGMA secure_delete = ON;", + 2 => "PRAGMA secure_delete = FAST;", + _ => SecureDeleteOff, + }; // Cache common LIMIT values using FrozenDictionary for O(1) lookup private static readonly FrozenDictionary CachedLimits = new Dictionary diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index f8144cf..da64bd5 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -44,6 +44,10 @@ private const string /// private const int PendingIndexShapeVersion = 0; + // SQLITE_FULL: the result code SQLite reports when the volume has no room for a + // write, which is the one failure the compaction skips rather than raises. + private const int SqliteFull = 13; + // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); @@ -2746,17 +2750,19 @@ private static HashSet ReadIndexNames(SqliteConnection conn) /// the index the previous release built for it; drops the per-type indexes a 4.x /// rollback recreated next to their replacements; deletes planner statistics an /// external ANALYZE left; and returns the pages all of that freed to the file - /// system — through a full VACUUM when the store was created without - /// incremental auto-vacuum (every 4.x store), which also converts it, or an in-place + /// system — by rewriting the store into a compacted copy and swapping it in when the + /// store was created without incremental auto-vacuum (every 4.x store), which also + /// converts it (see ), or by an in-place /// incremental_vacuum when at least a tenth of the file is free. Idempotent: /// with nothing pending it reads the schema and writes nothing, so calling it on /// every launch is fine. /// /// Holds the database's single connection for the duration, so every other /// operation on this instance waits: on a 1.8M-row, 3 GB store upgraded from 4.x the - /// drops, the rebuilds and the VACUUM took about 9, 9 and 5 s, 26 s in all, and - /// the VACUUM needs free disk space for a copy of the file. The work runs on the - /// calling thread — Microsoft.Data.Sqlite executes synchronously, so + /// drops and the rebuilds took about 9 s each, and the compaction needs free disk + /// space for the compacted copy — the live pages, about a third of that file — and is + /// skipped, to be retried by the next call, when the space is not there. The work + /// runs on the calling thread — Microsoft.Data.Sqlite executes synchronously, so /// does not move it off the caller by itself — and must /// not be called from a UI thread. /// @@ -2765,11 +2771,16 @@ public void Optimize() { ArgumentNullException.ThrowIfNull(_connection); - _connection - .WithConnectionBlock( - _connectionGate, - static conn => OptimizeStore(conn), - _persistConnection); + _connectionGate.Wait(); + + try + { + OptimizeStore(); + } + finally + { + _connectionGate.Release(); + } } /// @@ -2780,33 +2791,199 @@ public void Optimize() /// /// A token to cancel the asynchronous operation. /// A ValueTask containing true when the store was optimized. - public ValueTask OptimizeAsync(CancellationToken cancellationToken = default) + public async ValueTask OptimizeAsync(CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(_connection); - return _connection - .WithConnectionBlockAsync( - _connectionGate, - static conn => OptimizeStore(conn), - _persistConnection, - cancellationToken); + await _connectionGate.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + OptimizeStore(); + } + finally + { + _connectionGate.Release(); + } + + return true; } - private static bool OptimizeStore(SqliteConnection conn) + /// + /// Runs under the gate. The compaction replaces the connection, so nothing here + /// keeps the object the gate was entered with past that point. + /// + private void OptimizeStore() { + var conn = GatedConnection(); + try { - ExecuteNonQuery(conn, Queries.DropLegacyIndexes); - RebuildPendingIndexes(conn); - RemoveLeftoverStatistics(conn); - ReclaimFreeSpace(conn); + bool compact = ReadPragma(conn, Queries.AutoVacuumMode) == 0; + long secureDelete = compact ? ReadPragma(conn, Queries.SecureDelete) : 0; + + try + { + if (secureDelete != 0) + { + ExecuteNonQuery(conn, Queries.SecureDeleteOff); + } + + try + { + ExecuteNonQuery(conn, Queries.DropLegacyIndexes); + RebuildPendingIndexes(conn); + RemoveLeftoverStatistics(conn); + } + finally + { + if (secureDelete != 0) + { + ExecuteNonQuery(conn, Queries.RestoreSecureDelete(secureDelete)); + } + } + + if (!compact) + { + ReclaimFreePages(conn); + } + } + catch (Exception ex) when (ex is not TychoException) + { + throw new TychoException("Failed to optimize database", ex); + } + + if (compact) + { + CompactStore(); + } } - catch (Exception ex) when (ex is not TychoException) + finally { - throw new TychoException("Failed to optimize database", ex); + ReleaseGatedConnection(); } + } - return true; + private SqliteConnection GatedConnection() + { + var conn = _connection ?? throw new TychoException("Please call 'Connect' before performing an operation"); + + if (!_persistConnection) + { + conn.Open(); + } + + return conn; + } + + private void ReleaseGatedConnection() + { + if (!_persistConnection) + { + _connection?.Close(); + } + } + + /// + /// Rewrites a store that has no incremental auto-vacuum (every 4.x store) into a + /// compacted copy next to the file, with VACUUM INTO, and swaps the copy in: + /// the connection closes, which checkpoints the WAL into the file; the -wal and + /// -shm files are deleted; the copy is renamed over the database; and the + /// connection reopens on it. Only the live pages are written, once, into the + /// database's own directory — no temp copy, nothing back through the WAL — so the free + /// space needed is the compacted size. The WAL goes before the rename because SQLite + /// checks a WAL only against its own header, so one left next to the new file would be + /// replayed into it. The connection holds the file exclusively, so a WAL still on disk + /// with frames after the close means the close could not checkpoint it and the file + /// may lack commits only the WAL holds; the copy is discarded instead. The database is + /// untouched until the rename, which is atomic: an interruption leaves the old file + /// working and at most a leftover copy, which the next call removes. Skipped, to be + /// retried by the next call, when the volume lacks the space, SQLite reports it full, + /// or such a WAL remains. Runs under the gate. + /// + private void CompactStore() + { + var connection = _connection!; + string compactedPath = _databasePath + Queries.CompactedFileSuffix; + + long liveBytes = + (ReadPragma(connection, Queries.PageCount) - ReadPragma(connection, Queries.FreelistCount)) + * ReadPragma(connection, Queries.PageSize); + + if (!HasFreeSpaceFor(liveBytes)) + { + return; + } + + File.Delete(compactedPath); + + try + { + ExecuteNonQuery(connection, Queries.SetIncrementalAutoVacuum); + + using var vacuum = connection.CreateCommand(); + vacuum.CommandText = Queries.VacuumInto; + vacuum.Parameters.Add(new SqliteParameter("$path", SqliteType.Text) { Value = compactedPath }); + vacuum.ExecuteNonQuery(); + } + catch (SqliteException ex) when (ex.SqliteErrorCode == SqliteFull) + { + File.Delete(compactedPath); + return; + } + catch (Exception ex) + { + File.Delete(compactedPath); + throw new TychoException("Failed to compact database", ex); + } + + connection.Dispose(); + SqliteConnection.ClearPool(connection); + _connection = null; + + string walPath = _databasePath + "-wal"; + + if (new FileInfo(walPath) is { Exists: true, Length: > 0 }) + { + File.Delete(compactedPath); + _connection = OpenConnection(_connectionScript); + return; + } + + try + { + File.Delete(walPath); + File.Delete(_databasePath + "-shm"); + File.Move(compactedPath, _databasePath, overwrite: true); + } + catch (Exception ex) + { + File.Delete(compactedPath); + _connection = OpenConnection(_connectionScript); + throw new TychoException("Failed to compact database", ex); + } + + _connection = OpenConnection(_connectionScript); + } + + /// + /// Whether the volume holding the database has room for and + /// an eighth more. True when the volume cannot be asked: the compaction then relies + /// on SQLite reporting a full disk, which leaves the database untouched. + /// + private bool HasFreeSpaceFor(long bytes) + { + try + { + string fullPath = Path.GetFullPath(_databasePath); + string directory = Path.GetDirectoryName(fullPath) ?? fullPath; + + return new DriveInfo(directory).AvailableFreeSpace >= bytes + (bytes / 8); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return true; + } } /// @@ -2904,24 +3081,16 @@ private static void RemoveLeftoverStatistics(SqliteConnection conn) } /// - /// Returns freed pages to the file system. A store created without incremental - /// auto-vacuum — every 4.x store: its connect script set the pragma after - /// journal_mode = WAL, which fixed the mode at NONE — can only shrink through - /// a full VACUUM, which rewrites the file and converts it, so later calls take - /// the in-place path; that path runs when at least a tenth of the file is free, so a - /// store with a little churn is left alone. + /// Returns freed pages to the file system in place, on a store with incremental + /// auto-vacuum, when at least a tenth of the file is free, so a store with a little + /// churn is left alone. A store created without it — every 4.x store: its connect + /// script set the pragma after journal_mode = WAL, which fixed the mode at + /// NONE — is converted by instead, after which later + /// calls take this path. /// - private static void ReclaimFreeSpace(SqliteConnection conn) + private static void ReclaimFreePages(SqliteConnection conn) { - long autoVacuumMode = ReadPragma(conn, Queries.AutoVacuumMode); - - if (autoVacuumMode == 0) - { - ExecuteNonQuery(conn, Queries.FullVacuum); - return; - } - - if (autoVacuumMode != 2) + if (ReadPragma(conn, Queries.AutoVacuumMode) != 2) { return; } @@ -2957,44 +3126,61 @@ private static long ReadPragma(SqliteConnection conn, string pragma) /// auto-vacuum mode this runs a cheap in-place incremental_vacuum. On a /// legacy database that was created without incremental auto-vacuum (e.g. by an /// older version, or before the auto_vacuum ordering fix), incremental_vacuum - /// is a no-op, so this instead runs a one-time full VACUUM that both reclaims - /// the space and converts the database to incremental auto-vacuum for the future. + /// is a no-op, so this instead rewrites the database into a compacted copy and swaps + /// it in, which both reclaims the space and converts the database to incremental + /// auto-vacuum for the future; that needs free disk space for the compacted copy and + /// is skipped when the space is not there (see ). /// public void Cleanup(bool shrinkMemory = true, bool vacuum = false) { ArgumentNullException.ThrowIfNull(_connection); - _connection - .WithConnectionBlock( - _connectionGate, - (shrinkMemory, vacuum), - static (conn, state) => + _connectionGate.Wait(); + + try + { + var conn = GatedConnection(); + + try + { + bool compact = false; + + try { - try + if (shrinkMemory) { - if (state.shrinkMemory) - { - ExecuteNonQuery(conn, Queries.ShrinkMemory); - } + ExecuteNonQuery(conn, Queries.ShrinkMemory); + } - if (!state.vacuum) + if (vacuum) + { + compact = ReadPragma(conn, Queries.AutoVacuumMode) == 0; + + if (!compact) { - return; + ExecuteNonQuery(conn, Queries.IncrementalVacuum); } - - // incremental_vacuum only reclaims space when the database is in - // INCREMENTAL (2) auto-vacuum mode; a legacy/NONE database needs - // the full VACUUM, which also converts it. - ExecuteNonQuery( - conn, - ReadPragma(conn, Queries.AutoVacuumMode) == 2 ? Queries.IncrementalVacuum : Queries.FullVacuum); - } - catch (Exception ex) - { - throw new TychoException("Failed to clean up database", ex); } - }, - _persistConnection); + } + catch (Exception ex) + { + throw new TychoException("Failed to clean up database", ex); + } + + if (compact) + { + CompactStore(); + } + } + finally + { + ReleaseGatedConnection(); + } + } + finally + { + _connectionGate.Release(); + } } /// @@ -3239,34 +3425,23 @@ private static string ToSafeIdentifier(string derivedTypeName) private SqliteConnection BuildConnection() { - var connection = new SqliteConnection(_dbConnectionString); + _connectionGate.Wait(); - connection - .WithConnectionBlock( - _connectionGate, - ConnectionScript(), - static (conn, script) => - { - conn.Open(); - - // Verified once per process (see EnsureJsonSupport). - EnsureJsonSupport(conn); - - using var command = conn.CreateCommand(); - - // Profile PRAGMAs + idempotent schema/index creation. Composed from - // library constants and numeric profile values only (no user input). -#pragma warning disable CA2100 - command.CommandText = script; -#pragma warning restore CA2100 - - command.ExecuteNonQuery(); + try + { + var connection = OpenConnection(ConnectionScript()); - RemoveLeftoverStatistics(conn); - }, - _persistConnection); + if (!_persistConnection) + { + connection.Close(); + } - return connection; + return connection; + } + finally + { + _connectionGate.Release(); + } } private async ValueTask BuildConnectionAsync(CancellationToken cancellationToken = default) @@ -3275,16 +3450,33 @@ private async ValueTask BuildConnectionAsync(CancellationToken try { - var script = ConnectionScript(); - var connection = new SqliteConnection(_dbConnectionString); + return OpenConnection(ConnectionScript()); + } + finally + { + _connectionGate.Release(); + } + } + + /// + /// Opens a connection on the file and runs on it. Called + /// under the gate: by Connect, and by to reopen the store + /// it swapped in. A connection whose setup fails is disposed before the failure + /// propagates, so it does not keep the file's lock until the finalizer runs. + /// + private SqliteConnection OpenConnection(string script) + { + var connection = new SqliteConnection(_dbConnectionString); + try + { connection.Open(); // JSON support depends only on the process-wide native SQLite build, so // it is verified once and cached rather than re-queried on every connect. EnsureJsonSupport(connection); - await using var command = connection.CreateCommand(); + using var command = connection.CreateCommand(); // Profile PRAGMAs + idempotent schema/index creation. Composed from // library constants and numeric profile values only (no user input). @@ -3298,9 +3490,10 @@ private async ValueTask BuildConnectionAsync(CancellationToken return connection; } - finally + catch { - _connectionGate.Release(); + connection.Dispose(); + throw; } } From 4e82c76f2151e041340d0a0c5ec784fabd7d4805 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Tue, 20 Oct 2026 12:11:53 -0500 Subject: [PATCH 22/25] fix: connect to a read-only store when the leftover statistics cannot be deleted --- TychoDB.UnitTests/OptimizeTests.cs | 78 +++++++++++++++++++++++++++++- TychoDB/Tycho.cs | 13 ++++- 2 files changed, 87 insertions(+), 4 deletions(-) diff --git a/TychoDB.UnitTests/OptimizeTests.cs b/TychoDB.UnitTests/OptimizeTests.cs index 064e8ab..48c1612 100644 --- a/TychoDB.UnitTests/OptimizeTests.cs +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -20,8 +20,8 @@ namespace TychoDB.UnitTests; /// same-named 4.x index is recognised as stale instead of kept; the index a 4.x rollback /// leaves next to a current one is dropped, while one another declaration records as its /// own is kept; a current store is never written to by connect, by a declaration, or by -/// Optimize; and a pending definition that is not the statement Tycho built is -/// refused rather than run. +/// Optimize; a store on a read-only file still connects; and a pending definition +/// that is not the statement Tycho built is refused rather than run. /// [TestClass] public class OptimizeTests @@ -489,6 +489,67 @@ public async Task BothOverloads_UnderOneName_LeaveEachOthersIndexAlone() ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(manual); } + [TestMethod] + public async Task Connect_OnAReadOnlyFile_LeavesTheStatisticsAndSucceeds() + { + if (OperatingSystem.IsWindows()) + { + Assert.Inconclusive("Unix file modes are used to make the file read-only."); + } + + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + Execute(dbFile, "ANALYZE;"); + long statisticsRows = ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1"); + statisticsRows.ShouldBeGreaterThan(0); + + SqliteConnection.ClearAllPools(); + var mode = File.GetUnixFileMode(dbFile); + File.SetUnixFileMode(dbFile, UnixFileMode.UserRead | UnixFileMode.GroupRead | UnixFileMode.OtherRead); + + try + { + if (CanOpenForWriting(dbFile)) + { + Assert.Inconclusive("The file stays writable for this user, so the read-only connect cannot be exercised."); + } + + foreach (var autoOptimize in new[] { true, false }) + { + using var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync(); + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(100); + } + } + finally + { + // SQLite gives the -wal and -shm it creates the database file's mode. + SqliteConnection.ClearAllPools(); + + foreach (var file in new[] { dbFile, dbFile + "-wal", dbFile + "-shm" }.Where(File.Exists)) + { + File.SetUnixFileMode(file, mode); + } + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(statisticsRows); + + // Writable again, the next connect deletes them. + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(0); + } + [TestMethod] public async Task Optimize_RefusesATamperedPendingDefinition() { @@ -721,6 +782,19 @@ private static void WriteDefinition(string dbFile, string definition) command.ExecuteNonQuery().ShouldBe(1); } + private static bool CanOpenForWriting(string dbFile) + { + try + { + using var stream = new FileStream(dbFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); + return true; + } + catch (UnauthorizedAccessException) + { + return false; + } + } + /// The main file's bytes, once every pooled connection has closed and checkpointed. private static string FileHash(string dbFile) { diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index da64bd5..bc5d315 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -3462,7 +3462,10 @@ private async ValueTask BuildConnectionAsync(CancellationToken /// Opens a connection on the file and runs on it. Called /// under the gate: by Connect, and by to reopen the store /// it swapped in. A connection whose setup fails is disposed before the failure - /// propagates, so it does not keep the file's lock until the finalizer runs. + /// propagates, so it does not keep the file's lock until the finalizer runs. The + /// statistics delete is best-effort here, as the PRAGMA optimize it replaced + /// was: a store on a read-only file or a full volume connects, and the planner stays + /// misled until a connect that can write; reports the failure. /// private SqliteConnection OpenConnection(string script) { @@ -3486,7 +3489,13 @@ private SqliteConnection OpenConnection(string script) command.ExecuteNonQuery(); - RemoveLeftoverStatistics(connection); + try + { + RemoveLeftoverStatistics(connection); + } + catch (SqliteException) + { + } return connection; } From 37d05afa21728b536da5cd8a2b6f60fee796aad0 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Tue, 20 Oct 2026 12:12:20 -0500 Subject: [PATCH 23/25] fix: set the package version to 5.4.0 --- Directory.build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.build.props b/Directory.build.props index dd97293..ec3172c 100644 --- a/Directory.build.props +++ b/Directory.build.props @@ -3,7 +3,7 @@ true latest $(NoWarn);CS1591 - 5.0.0 + 5.4.0 Eight-Bot, Inc. From 9af4232a02cf7f2f388b9f77811e4c4dc6597b2f Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Tue, 20 Oct 2026 12:12:47 -0500 Subject: [PATCH 24/25] docs: describe the compaction swap, the definition check and the read-only connect --- CHANGELOG.md | 58 ++++++++++++++++++++--------- README.md | 14 ++++--- docs/planner-statistics-sampling.md | 54 +++++++++++++++++++++------ 3 files changed, 91 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6985185..3e8bbf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,9 +24,11 @@ delete the `sqlite_stat1` rows an earlier release or an external `ANALYZE` left and reload, so an upgraded store is repaired on its first connect whether or not `autoOptimize` is on; nothing is written when there are no rows, and the table is never - dropped, since `ANALYZE sqlite_master` would recreate it. The one thing statistics could - add — ranking two single-property indexes when a filter ANDs both — is what a composite - index is for. + dropped, since `ANALYZE sqlite_master` would recreate it. At connect the delete is + best-effort, as the `PRAGMA optimize` it replaces was: a store on a read-only file or a + full volume still connects, with the planner misled until a connect that can write, while + `Optimize()` reports the failure. The one thing statistics could add — ranking two + single-property indexes when a filter ANDs both — is what a composite index is for. - **The string overload of `CreateIndex` silently kept the index 4.x built.** It names its index exactly as 4.x did, so its `CREATE INDEX IF NOT EXISTS` met the 4.x index and did nothing, while the metadata recorded the new definition as built: queries still matched @@ -41,7 +43,10 @@ were maintained on every write and the planner could prefer the wider one. `CreateIndex` now probes the legacy name on the current path and drops it (left to `Optimize()` under `autoOptimize: false`), `Optimize()` sweeps it for every recorded index, and `DropIndex` - drops it together with the index. + drops it together with the index. A legacy name that another declaration records as its + own index is left alone by all three: the string overload names its index exactly as 4.x + did, so an app declaring one name through both overloads keeps both indexes instead of + dropping and rebuilding the string overload's on every launch. - **Connecting to an existing store wrote page 1 every time.** `PRAGMA auto_vacuum = INCREMENTAL` only takes effect on a database being created, but on an auto-vacuum store it stores the mode the file already has, in a write transaction that bumps the change @@ -64,21 +69,38 @@ existing index serves is built at once either way. `Optimize()` / `OptimizeAsync()` then do, in one hold of the connection: the four drops, every pending rebuild (each in a transaction of its own, so an interruption leaves either the old index or the new one), - the orphan drops a rollback needs, the statistics delete, and a full `VACUUM` when the + the orphan drops a rollback needs, the statistics delete, and a compaction when the store has no incremental auto-vacuum — every 4.x store, whose connect script set the - pragma too late — which returns the freed pages to the file system (3.06 GB → 1.03 GB in - 5 s on that store; the whole call took 26 s) and converts the store, or an in-place - `incremental_vacuum` when at least a tenth of the file is free. None of these timings - changed with the file cold on disk. With the whole-table 4.x indexes gone, 50,000-row - bulk writes on that store ran 2.1x faster for an indexed type (38k → 80k rows/s) and 3x - for an unindexed one (62k → 190k rows/s), and partition deletes 2.2–2.7x. Idempotent: - with nothing pending they read the schema and write nothing, so calling them on every - launch is fine. They hold the single connection for - the duration, so every other operation on the instance waits, and run on the calling - thread — Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not - move the work off the caller — so call them from a background thread; the `VACUUM` needs - free disk space for a copy of the file. `ListIndexes()` lists a pending index with the - definition it will get. + pragma too late — or an in-place `incremental_vacuum` when at least a tenth of the file + is free. The compaction rewrites the live pages into a copy next to the database with + `VACUUM INTO`, closes the connection, renames the copy over the file and reopens on it: + it converts the store, returns the freed pages to the file system (3.06 GB → 1.03 GB on + that store, 2.37 GB → 1.04 GB on a 1.76M-row one), needs free disk space for the + compacted copy only — a full `VACUUM` writes the data twice, to a temp copy and back + through the WAL, and failed with the disk full where this succeeds — and leaves the + database untouched until the rename, which is atomic; the WAL is deleted before the + rename, since SQLite checks a WAL only against its own header and would replay a leftover + one into the new file, so an interruption costs at most a leftover copy the next call + removes. It is skipped, to be retried by the next call, when + the volume lacks the space, SQLite reports it full, or the WAL survives the close + because the close could not checkpoint it; under SQLCipher the drops run with + `secure_delete` off when a compaction follows, since the setting otherwise zeroes every + freed page through the WAL and the drops need free space equal to the index. With the + whole-table 4.x indexes gone, 50,000-row bulk writes on that store ran 2.1x faster for + an indexed type (38k → 80k rows/s) and 3x for an unindexed one (62k → 190k rows/s), and + partition deletes 2.2–2.7x; none of the timings changed with the file cold on disk. + Idempotent: with nothing pending they read the schema and write nothing, so calling them + on every launch is fine. They hold the single connection for the duration, so every + other operation on the instance waits, and run on the calling thread — + Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not move the + work off the caller — so call them from a background thread. `Cleanup(vacuum: true)` + compacts a store without incremental auto-vacuum the same way. `ListIndexes()` lists a + pending index with the definition it will get. A pending definition is read back out of + the file before it runs, so `Optimize()` re-checks it rather than trusting it: the + statement is taken apart into the paths and type it indexes and must build again byte + for byte, and one that does not — a second statement appended, an expression TychoDB + never emits — is refused with a `TychoException` naming the index, the store left as it + was. ## 5.3.1 — 2026-10-05 diff --git a/README.md b/README.md index 49eba41..0fc7565 100644 --- a/README.md +++ b/README.md @@ -516,8 +516,11 @@ This matters for how they behave: `autoOptimize: false` to defer both: connect and the declarations then cost about 140 ms, `CreateIndex` records each declaration as pending while queries keep using the index 4.x built, and `Optimize()` / `OptimizeAsync()` — called from a background - thread — do the drops, the rebuilds, and a `VACUUM` that returns the freed pages to the - file system (3.06 GB to 1.03 GB in 5 s; 26 s for the whole call). A declaration no + thread — do the drops, the rebuilds, and a compaction that returns the freed pages to + the file system (3.06 GB to 1.03 GB on that store): the live pages are written into a + copy next to the database with `VACUUM INTO` and the copy is swapped in, so the free + space needed is the compacted copy, the file is untouched until an atomic rename, and + the step is skipped and retried next time when the space is not there. A declaration no existing index serves is built at once either way. - **The upgrade pays back on every write.** With the whole-table 4.x indexes gone, 50,000-row bulk writes on that store ran 2.1x faster for an indexed type (38k to 80k @@ -631,9 +634,10 @@ db.Cleanup(shrinkMemory: true, vacuum: true); // Do the one-time work an upgraded store needs: drop the indexes 4.x created, build the // indexes declared under autoOptimize: false, drop what a 4.x rollback left behind, and -// VACUUM. A no-op once done. Holds the connection for the duration — every other -// operation on this instance waits; 26 s on a 1.8M-row, 3 GB store upgraded from 4.x — and -// runs on the calling thread, so call it from a background thread, never the UI thread. +// compact the file (skipped when the disk lacks room for the compacted copy). A no-op once +// done. Holds the connection for the duration — every other operation on this instance +// waits; tens of seconds on a 1.8M-row, 3 GB store upgraded from 4.x — and runs on the +// calling thread, so call it from a background thread, never the UI thread. await Task.Run(() => db.Optimize()); ``` diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index ea645c8..078df5f 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -113,10 +113,12 @@ statistics, and that finding is reversed. - `TychoDB.UnitTests/OptimizeTests.cs` — the upgrade path from 4.4.2 through Tycho's own API: a store with 4.4.2's per-type and built-in indexes and no incremental auto-vacuum, declared under `autoOptimize: false` (pending, served by the 4.4.2 index) and then - optimized (rebuilt, drops done, `VACUUM` run, store converted, nothing written on the + optimized (rebuilt, drops done, store compacted and converted, nothing written on the next launch); the same store under `autoOptimize: true`; the string overload's - same-named 4.4.2 index; the orphan a rollback leaves; and a current store that connect, - the declarations and `Optimize` leave byte-identical. + same-named 4.4.2 index; the orphan a rollback leaves; a current store that connect, the + declarations and `Optimize` leave byte-identical; and the compaction itself — the + instance keeps serving on the swapped-in file, a leftover copy is replaced, it works + without a persistent connection, and `Cleanup(vacuum: true)` takes the same path. Bound parameters are fine in the library: SQLite re-plans when a bound value touches a partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic @@ -144,13 +146,29 @@ six whole-table per-type indexes go too (table below). `autoOptimize: false` connects without the drops and records each `CreateIndex` whose index 4.x built as pending, leaving that index to serve queries — about 140 ms for the connect and six declarations on that store; `Optimize`/`OptimizeAsync` then do the drops, -the rebuilds, the orphan sweep a 4.x rollback needs, the statistics delete, and a full -`VACUUM` that returns the freed pages — 2 GB on that store, in 5 s; 26 s for the whole -call — since a 4.x store has no incremental auto-vacuum and nothing else can. The numbers -are in the table below. Both hold the single connection for the -duration and run on the calling thread — Microsoft.Data.Sqlite executes synchronously, so -the async form alone does not move the work off the caller — so apps call them from a -background thread. +the rebuilds, the orphan sweep a 4.x rollback needs, the statistics delete, and a +compaction that returns the freed pages — 2 GB on that store — since a 4.x store has no +incremental auto-vacuum and nothing else can. The numbers are in the table below. Both +hold the single connection for the duration and run on the calling thread — +Microsoft.Data.Sqlite executes synchronously, so the async form alone does not move the +work off the caller — so apps call them from a background thread. + +The compaction is `VACUUM INTO` a copy next to the database, then a swap: the connection +closes, the copy is renamed over the file, and the connection reopens on it. A full +`VACUUM` writes the data twice — into a temp copy, then back into the file through the +WAL, which grew to 1.04 GB on the 2.37 GB store — so it needs free space for about two +compacted copies and, on a 49 MB store with 75 MB free, failed with `database or disk is +full`, left `temp_store = FILE` on the connection, and was retried on every call. `VACUUM +INTO` writes the live pages once, needs free space for one compacted copy, uses no temp +directory, and leaves the database untouched until the rename, which is atomic: the same +store compacted on the same volume. The `-wal` and `-shm` are deleted before the rename, +not after: SQLite checks a WAL only against its own header, so a WAL an interruption left +next to the new file would be replayed into it. `Optimize` checks the volume first and skips the +compaction, to retry on the next call, when the space is not there or SQLite reports the +disk full, and discards the copy when the WAL survives the close, which happens only +when the close could not checkpoint it. Under SQLCipher, whose `secure_delete` default zeroes every freed page through +the WAL — dropping a 528 KB index wrote 544 KB of WAL, against 12 KB with the setting off +— the drops run with it off when a compaction follows, and the setting is restored after. ## Measured on the real store @@ -164,7 +182,7 @@ brand, origin and load date; a distance by SPLC pair; a zip3; a zip. | Connect | 72 ms | | Six `CreateIndex`, all recorded pending, no DDL | 69 ms (67 of it the first call's JIT) | | Lookups while pending, on the 4.4.2 indexes | pricing 5.3 ms, SPLC 0.2 ms, zip3 and zip 0.05 ms | -| `Optimize()`: four drops, six rebuilds, `VACUUM`, conversion | 26.3 s | +| `Optimize()`: four drops, six rebuilds, full `VACUUM` (before the compaction below), conversion | 26.3 s | | Lookups after | pricing 0.64 ms, the others 0.05 ms | | File | 3,063 MB → 1,030 MB, `auto_vacuum` 2, freelist 0 | | Next launch: Connect, six `CreateIndex`, `Optimize()` | 44 ms, 34 ms, 1 ms | @@ -174,11 +192,23 @@ brand, origin and load date; a distance by SPLC pair; a zip3; a zip. | Connect, the four drops | 9.2 s | | Six `CreateIndex` inline, drop the 4.4.2 index and build | 9.0 s (0.7–4.7 s each) | | File after launch | 2,922 MB, 476,124 free pages, still NONE | -| `Optimize()` on the next launch, the `VACUUM` alone | 5.4 s → 1,030 MB; a further call 1 ms | +| `Optimize()` on the next launch, the full `VACUUM` alone | 5.4 s → 1,030 MB; a further call 1 ms | The string overload's same-named 4.4.2 index on a 5,000-row store: 4 ms to detect the mismatch and record it pending, 15 ms for `Optimize()` to rebuild it, 9 ms inline. +The compaction that replaced the full `VACUUM`, measured through the library on a copy of +another 4.4.2 pricing store (1,763,583 rows, 2,374 MB, the same eleven indexes, e_sqlite3 +3.50.3, NVMe, warm): `Optimize()` under `autoOptimize: false` — the four drops, six +rebuilds, `VACUUM INTO` and the swap — 19.0 s, against 22.4 s with the full `VACUUM` on +the same store, the file 2,374 MB → 1,037 MB with +the WAL never above 12 MB where the full `VACUUM` had taken it to 1,043 MB; lookups on +the swapped-in file 0.56 / 0.05 / 0.04 / 0.04 ms without reconnecting; the next launch's +`Optimize()` 1.5 ms. The same 49 MB store on a volume with 75 MB free: the full `VACUUM` +failed with the disk full, the compaction took 153 ms; with 16 MB free it was skipped in +2.5 ms, the store untouched and in use. Through SQLCipher with a key, the compaction of +that store took 1.4 s and the copy opened under the same key with `secure_delete` back on. + Cold: the same runs with the file copied without caching (`F_NOCACHE`; a system purge needs root), verified cold by a first sequential read at half the cached speed. Every phase was within noise of the warm run — deferred connect 78 ms and declarations 62 ms, first From be39d8af0caea3de451a27b3d88887d71c81863d Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Wed, 21 Oct 2026 11:17:20 -0500 Subject: [PATCH 25/25] docs: add the history of the planner statistics work and the reasons for each step --- planner-statistics-history.md | 206 ++++++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 planner-statistics-history.md diff --git a/planner-statistics-history.md b/planner-statistics-history.md new file mode 100644 index 0000000..c6edb02 --- /dev/null +++ b/planner-statistics-history.md @@ -0,0 +1,206 @@ +# Query Planner Statistics: History and Decisions + +TychoDB stores every object in one table, `JsonValue`. Two kinds of index matter here: + +- **General index**: `(FullTypeName, Partition)`, shared by all types. +- **Per-type index**: a partial index that `CreateIndex` builds for one property of one type. + +SQLite's query planner chooses between them. If `ANALYZE` has stored statistics in `sqlite_stat1`, the planner uses them; if not, it uses its built-in rules. + +--- + +## 1. The 5.3.1 problem + +**What happened:** Lookups on an indexed property became slow on large stores. On a 1.68M-row store, a lookup took 82–366 ms instead of 0–1 ms. The results were still correct. + +**Why:** 5.3.1 ran `ANALYZE` with `analysis_limit = 400`, so SQLite read only the first 400 entries of each index. That sample told the planner each type had about 81 rows, but the largest type had 586,986. So the planner picked the general index and read every row of the type on each lookup. + +--- + +## 2. First fix: full statistics + +**Changed:** `ANALYZE` ran without a limit after `CreateIndex`, and once on stores that already held sampled statistics. + +**Why:** Full statistics give the planner the right row counts, so it picks the per-type index again. + +**Result:** Lookups were fast again, but a full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store. + +--- + +## 3. Connecting became slow + +**What happened:** On the first launch after upgrading, connecting took 10–34 s on MoveScoutPro's device stores. + +**Why:** Connecting did two slow things. It dropped four indexes that 4.x created and 5.x no longer needs, which took 3.8–9.3 s, and it ran the statistics work. + +--- + +## 4. Opt-out for the slow connect + +**Changed:** Added `autoOptimize: false`, plus `Optimize()` / `OptimizeAsync()` to do the same work later. + +**Why:** It lets an app connect fast and do the slow, one-time work on a background thread. + +--- + +## 5. `PRAGMA optimize` could not be trusted + +**What happened:** +- **Sampling came back:** by default, `PRAGMA optimize` limits `ANALYZE` to 2,000 rows, which recreated the 5.3.1 problem. +- **It re-analyzed on every call:** with the limit removed, it estimated a 1.84M-row store at 174,370 rows, so it decided the table had grown and re-analyzed on every call, 20–30 s each time. + +**Changed:** TychoDB stopped using `PRAGMA optimize`, and decided for itself when statistics were out of date. + +**Why:** SQLite's own check gave wrong answers on real data. + +--- + +## 6. Step back: no statistics at all + +**Changed:** All statistics work was removed. Connecting now deletes any statistics an earlier release left behind. The 4.x index drops stay. + +**Why:** +- **Each fix needed another fix,** so it was worth asking whether statistics were needed at all. +- **Built-in rules choose correctly without them.** The planner picks the right index for every single-index query TychoDB runs: equality, range, sort with a limit, an unindexed property, a whole type, and a count. +- **Nothing left to go wrong:** with no statistics, nothing can be sampled or go out of date. +- **The drops make writes faster:** bulk writes are 25–45% faster without the old indexes. + +**Known trade-off:** when a query filters on two indexed properties, the planner can't tell which index is better, so it picks one by rule. This was accepted without being measured. + +--- + +## 7. Tested on real device stores + +MoveScoutPro's test suite ran on four device stores (682k–1.85M rows, 2.4–3.2 GB), with `autoOptimize: false`: + +| | Stock 5.3.1 | This branch | +|---|---|---| +| First connect after upgrade | 10–34 s | 8–40 ms | +| `Optimize()`, first call | – | 3.8–9.3 s | +| `Optimize()`, later calls | – | 0–1 ms | +| App login to launch page | 18.2 s | 8.8 s (4.4.2: 9.3 s) | + +Results matched 4.4.2 for every read and write. + +--- + +## 8. Rename (later reset) + +**Changed:** `autoOptimize` became `dropLegacyIndexes`, and `Optimize()` became `DropLegacyIndexes()`. + +**Why:** At that point dropping the old indexes was the only work left, so the names should say that. + +**Now:** Reset off the branch. The branch keeps `autoOptimize` / `Optimize()`, which now do more than the drops (step 12). + +--- + +## 9. Commit 120fc5c: statistics come back + +**Why:** It found two real problems with step 6: + +1. **Two indexed filters:** the planner used whichever index was created last. That cost 4.6 ms instead of 0.02 ms at 40,000 rows. +2. **Writes on every connect:** each connect dropped and re-created `sqlite_stat1`, which changes the schema twice. With `persistConnection: false`, that happens on every operation. + +**Changed:** +- **Gathered on index build:** a full `ANALYZE JsonValue` ran whenever `CreateIndex` built an index. +- **General index overwritten:** its statistics were set to half the table's row count, so it only wins when one value covers more than half the table. +- **One-time repair:** stores with sampled statistics were fixed once, and `PRAGMA user_version` recorded that it had run. + +--- + +## 10. 120fc5c reverted + +**Why:** +- **Statistics never refreshed.** They were taken once, when an index was built. In two synthetic tests (544k rows) they went out of date and lookups took 174 ms and 180 ms instead of 0 ms. That's the 5.3.1 problem again, and nothing fixed it. +- **Upgrades got slower.** Every index build ran a full `ANALYZE`, which takes 3.2–17.5 s on real stores, and a 4.x upgrade rebuilds every index. +- **No gain on a real store.** On a 1.8M-row, 3 GB production store, plans and timings were the same with and without statistics. +- **Composite indexes cover two filters.** A query filtering on two properties is served by a composite index, which needs no statistics. The README now says so. + +**Kept:** the connect-write problem it found, fixed in step 11. + +--- + +## 11. Connecting writes nothing + +**What happened:** Connect wrote to the file every time, for two reasons: +- It dropped and re-created `sqlite_stat1`. +- It ran `PRAGMA auto_vacuum = INCREMENTAL`, which rewrites the first page of an existing store. + +**Changed:** +- **Statistics:** connect deletes leftover `sqlite_stat1` rows only when there are any, and never drops the table. +- **Auto-vacuum:** the pragma runs only for a new file. + +**Why:** A write on every connect is wasted work, and with `persistConnection: false` it happened on every operation. + +**Result:** Connecting to a current store leaves the file byte-identical. + +--- + +## 12. Defer the index rebuilds too + +**What happened:** On a 4.x upgrade, each first `CreateIndex` drops the old 4.x index and builds the new one. On a 1.8M-row, 3 GB store that took 0.7–4.7 s per index, 9.0 s for six, on top of 9.2 s of drops at connect. + +**Changed:** +- **Pending indexes:** with `autoOptimize: false`, `CreateIndex` marks the index as pending, and the old 4.x index keeps serving queries. +- **`Optimize()` does the rest:** the drops, the pending rebuilds, and a `VACUUM` to return the freed space. 4.x stores never got incremental auto-vacuum, so the space can only come back this way. +- **Two related fixes:** + - The string overload of `CreateIndex` no longer keeps the 4.x index by mistake. + - Indexes a 4.x rollback recreated are dropped. + +**Result** on that store: + +| | | +|---|---| +| Connect plus six `CreateIndex` | about 140 ms | +| `Optimize()` | 26.3 s | +| File size | 3,063 MB → 1,030 MB | +| Next launch: connect, six `CreateIndex`, `Optimize()` | 44 ms, 34 ms, 1 ms | +| Bulk writes afterwards | 2.1x faster (indexed type), 3x (unindexed) | + +--- + +## 13. Compact with `VACUUM INTO` instead of `VACUUM` + +**What happened:** A full `VACUUM` writes the data twice: into a temp copy, then back through the WAL, which grew to 1.04 GB on a 2.37 GB store. It needs room for about two copies. On a 49 MB store with 75 MB free it failed with "database or disk is full", and was retried on every call. + +**Changed:** `Optimize()` now: +1. writes a compacted copy with `VACUUM INTO`, +2. closes the connection, +3. deletes the old `-wal` and `-shm` files, +4. renames the copy over the database, +5. reopens. + +It skips the compaction, and retries on the next call, when there isn't room or a WAL with data is still there after the close. + +**Why:** +- **One copy:** `VACUUM INTO` writes the data once, so it only needs room for one compacted copy. +- **Safe interruption:** the database isn't touched until the rename, which is atomic. +- **WAL first:** SQLite would replay an old WAL into the new file, so the WAL is deleted before the rename. + +**Result:** + +| Store | Full `VACUUM` | `VACUUM INTO` | +|---|---|---| +| 1.76M rows, 2,374 MB: whole `Optimize()` | 22.4 s | 19.0 s | +| Same store: largest WAL | 1,043 MB | 12 MB | +| 49 MB store, 75 MB free | failed, disk full | 153 ms | +| 49 MB store, 16 MB free | – | skipped in 2.5 ms | + +--- + +## 14. Smaller fixes + +- **Both overloads, one name:** when the same index name is declared through both `CreateIndex` overloads, each now leaves the other's index alone. Before, one dropped and rebuilt the other's index on every launch. +- **Pending definitions are checked:** a pending index's saved definition is rebuilt from its parts and compared exactly before `Optimize()` runs it, and anything else is refused. It's read back from the file, so it could have been changed. +- **Read-only files:** connecting works even when leftover statistics can't be deleted. +- **Version:** set to 5.4.0. + +--- + +## Where it ends up + +- **No statistics:** no planner statistics are gathered, and connect deletes leftover ones only if there are any. +- **Quiet connect:** connecting to a current store writes nothing. +- **`autoOptimize: true` (default):** connect drops the 4.x indexes and `CreateIndex` rebuilds on the spot. +- **`autoOptimize: false`:** connect and `CreateIndex` take milliseconds, and `Optimize()` on a background thread does the drops, rebuilds and compaction. +- **Two filters:** filtering on two properties needs a composite index.