From c7e1ff27b3e5f22c3bf9e3bb98d7e7c1837bc470 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 01/11] test: run test classes one at a time so a pool clear cannot hit another class --- TychoDB.UnitTests/TychoDbTests.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/TychoDB.UnitTests/TychoDbTests.cs b/TychoDB.UnitTests/TychoDbTests.cs index 312678b..2a1fdc3 100644 --- a/TychoDB.UnitTests/TychoDbTests.cs +++ b/TychoDB.UnitTests/TychoDbTests.cs @@ -13,7 +13,9 @@ using Shouldly; using TychoDB; -[assembly: Parallelize(Scope = ExecutionScope.ClassLevel)] +// SqliteConnection.ClearAllPools, which releases a closed store's EXCLUSIVE lock, can dispose +// a connection another thread is opening, so no two test classes may run at once. +[assembly: DoNotParallelize] namespace TychoDB.UnitTests; From 86e9ec4667a6079426168dd2d852a8ce127852ff Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 02/11] fix: gather no planner statistics, delete what earlier releases left, and stop rewriting page 1 at connect --- TychoDB.Benchmarks/Diagnostics.cs | 2 +- TychoDB.UnitTests/ConfigurationTests.cs | 13 +- TychoDB.UnitTests/IndexDdlTests.cs | 20 +- TychoDB.UnitTests/PlannerStatisticsTests.cs | 526 ++++++++++++++++++++ TychoDB.UnitTests/StoreFixture.cs | 299 +++++++++++ TychoDB/Queries.cs | 55 +- TychoDB/Tycho.cs | 207 ++++---- 7 files changed, 997 insertions(+), 125 deletions(-) create mode 100644 TychoDB.UnitTests/PlannerStatisticsTests.cs create mode 100644 TychoDB.UnitTests/StoreFixture.cs 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/ConfigurationTests.cs b/TychoDB.UnitTests/ConfigurationTests.cs index 2e0646d..ada442e 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() { @@ -108,7 +119,7 @@ public async Task Cleanup_MigratesLegacyNoneDatabase_AndReclaimsSpace() await db.DeleteObjectsAsync(); // incremental_vacuum would be a no-op here; Cleanup must detect NONE and - // run a full VACUUM to reclaim space and convert to incremental. + // compact the store to reclaim space and convert to incremental. db.Cleanup(shrinkMemory: true, vacuum: true); } diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 4576e26..3513b30 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,13 @@ 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. 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_master WHERE type = 'table' AND name = 'sqlite_stat1'"; - Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture).ShouldBe(1); + command.CommandText = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1'"; + command.ExecuteScalar().ShouldBeNull(); } [TestMethod] @@ -426,12 +427,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 new file mode 100644 index 0000000..4770608 --- /dev/null +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -0,0 +1,526 @@ +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 chooses the right index for every query shape TychoDB emits with no +/// planner statistics at all, and that TychoDB gathers none. +/// +/// 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] +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 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 GroupIndexName = "group_idx"; + private const string SeqIndexName = "seq_idx"; + private const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; + 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; } + + public string Label { get; set; } + } + + [TestMethod] + public async Task CreateIndex_OnStoreWithManySmallTypesFirst_PartialIndexChosen() + { + 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, GroupIndexName); + + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); + } + + [TestMethod] + 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. + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.GroupId, GroupIndexName); + } + + 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, GroupIndexName); + + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); + } + + [TestMethod] + public async Task Connect_RemovesStatisticsLeftByAnEarlierRelease() + { + 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); + } + + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); + } + + [TestMethod] + public async Task Connect_DeletesLeftoverStatisticsOnce_ThenLeavesTheEmptyTableAlone() + { + var (path, dbName) = StoreFixture.NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await StoreFixture.BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(StoreFixture.Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, StoreFixture.IndexName); + } + + StoreFixture.ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'sqlite_stat1'").ShouldBe(0); + + StoreFixture.Execute(dbFile, "ANALYZE;"); + StoreFixture.ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBeGreaterThan(0); + + using (await StoreFixture.ReopenDb(path, dbName).ConnectAsync()) + { + } + + StoreFixture.ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(0); + StoreFixture.ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'sqlite_stat1'").ShouldBe(1); + + var hash = StoreFixture.FileHash(dbFile); + + using (await StoreFixture.ReopenDb(path, dbName).ConnectAsync()) + { + } + + StoreFixture.FileHash(dbFile).ShouldBe(hash); + } + + [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) = StoreFixture.NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await StoreFixture.BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(StoreFixture.Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, StoreFixture.IndexName); + } + + StoreFixture.Execute(dbFile, "ANALYZE;"); + long statisticsRows = StoreFixture.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 (StoreFixture.CanOpenForWriting(dbFile)) + { + Assert.Inconclusive("The file stays writable for this user, so the read-only connect cannot be exercised."); + } + + using var db = await StoreFixture.ReopenDb(path, dbName).ConnectAsync(); + await db.CreateIndexAsync(x => x.Seq, StoreFixture.IndexName); + await StoreFixture.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); + } + } + + StoreFixture.ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(statisticsRows); + + // Writable again, the next connect deletes them. + using (await StoreFixture.ReopenDb(path, dbName).ConnectAsync()) + { + } + + StoreFixture.ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(0); + } + + [TestMethod] + public async Task WithoutStatistics_EqualityUsesThePartialIndex() + { + var dbFile = await SeedIndexedStore(); + + var plan = Explain(dbFile, filter: GroupFilter()); + + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, GroupIndexName)}", Case.Sensitive); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); + } + + [TestMethod] + public async Task WithoutStatistics_RangeUsesThePartialIndex() + { + var dbFile = await SeedIndexedStore(); + + var plan = Explain( + dbFile, + filter: FilterBuilder.Create().Filter(FilterType.GreaterThan, x => x.Seq, WideRowCount - 1000)); + + plan.ShouldContain($"USING INDEX {ReadPhysicalIndexName(dbFile, SeqIndexName)}", Case.Sensitive); + plan.ShouldNotContain(GeneralIndexName, Case.Sensitive); + } + + [TestMethod] + public async Task WithoutStatistics_SortWithLimitUsesThePartialIndex() + { + var dbFile = await SeedIndexedStore(); + + var plan = Explain( + dbFile, + sort: SortBuilder.Create().OrderBy(SortDirection.Ascending, x => x.Seq), + top: 20); + + 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 WithoutStatistics_TwoIndexedEqualitiesUseOneOfThePartialIndexes() + { + var dbFile = await SeedIndexedStore(); + + var plan = Explain( + dbFile, + filter: GroupFilter().And().Filter(FilterType.Equals, x => x.Seq, 42)); + + 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 WithoutStatistics_UnindexedPropertyUsesTheGeneralIndex() + { + var dbFile = await SeedIndexedStore(); + + var plan = Explain( + dbFile, + filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Label, "row 7")); + + plan.ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + } + + [TestMethod] + public async Task WithoutStatistics_WholeTypeUsesTheGeneralIndex() + { + var dbFile = await SeedIndexedStore(); + + Explain(dbFile).ShouldContain($"USING INDEX {GeneralIndexName}", Case.Sensitive); + } + + [TestMethod] + public async Task WithoutStatistics_CountUsesTheGeneralIndexWithoutReadingRows() + { + var dbFile = await SeedIndexedStore(); + + Explain(dbFile, count: true).ShouldContain($"USING COVERING INDEX {GeneralIndexName}", Case.Sensitive); + } + + // ---------- assertions ---------- + private static void AssertGroupLookupUsesPartialIndex(string dbFile) + { + var plan = Explain(dbFile, filter: GroupFilter()); + + 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); + + /// 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(count ? Queries.SelectCountFromJsonValueWithFullTypeName : Queries.SelectDataFromJsonValueWithFullTypeName); + var parameters = new FilterParameters(); + + 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(); + +#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, 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); + return (string)command.ExecuteScalar(); + } + + /// + /// 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(); + + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + 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 ---------- + + /// A store with the wide type indexed on GroupId and Seq, and the small types ahead of it. + private static async Task SeedIndexedStore() + { + 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); + } + + var dbFile = Path.Combine(path, dbName); + SeedSmallTypes(dbFile); + 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); + for (int i = 0; i < WideRowCount; i++) + { + rows.Add(new WideModel { Key = $"wide-{i}", GroupId = GroupId(i), Seq = i, Label = $"row {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(); + } + + // ---------- 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.UnitTests/StoreFixture.cs b/TychoDB.UnitTests/StoreFixture.cs new file mode 100644 index 0000000..c775ec5 --- /dev/null +++ b/TychoDB.UnitTests/StoreFixture.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Shouldly; +using TychoDB; + +namespace TychoDB.UnitTests; + +/// +/// A store as an earlier release leaves it, and the means of opening and inspecting one, for +/// the tests of the upgrade path. +/// +internal static class StoreFixture +{ +#if ENCRYPTED + public const string DbPassword = "Password"; +#endif + + public const string IndexName = "seq_idx"; + public const string LegacyIndexName = "idx_seq_idx_Item"; + public const string ManualIndexName = "manual_idx"; + public const string ManualPhysicalName = "idx_manual_idx_Item"; + public const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; + + public const long LookupSeq = 42; + + public static readonly string[] BuiltInLegacyIndexNames = + { + "idx_jsonvalue_fulltypename", + "idx_jsonvalue_key_fulltypename", + "idx_jsonvalue_key_fulltypename_partition", + "idx_streamvalue_key_partition", + }; + + public static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); + + public class Item + { + public string Key { get; set; } + + public string Group { get; set; } + + public long Seq { get; set; } + } + + public readonly record struct MetadataRow( + string IndexName, + string FullTypeName, + string PhysicalName, + string Definition, + long ShapeVersion); + + /// + /// 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. + /// + public static async Task SeedLegacyStore(int rows = 100) + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(rows), 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. + public static string LegacyIndexDdl(string name) + => $"CREATE INDEX IF NOT EXISTS {name} ON JsonValue(FullTypeName, CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC));"; + + public static List Items(int rows = 100) + { + var items = new List(rows); + for (int i = 0; i < rows; i++) + { + items.Add(new Item + { + Key = $"item-{i}", + Group = "G" + (i % 10).ToString(CultureInfo.InvariantCulture), + Seq = i, + }); + } + + return items; + } + + public 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. + public 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(); + } + + public 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; + } + + public 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; + } + + public static long ReadPragma(string dbFile, string pragma) + => ReadScalar(dbFile, "PRAGMA " + pragma); + + public 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; + } + + public 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; + } + + public 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(); + } + + public 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. + public static string FileHash(string dbFile) + { + SqliteConnection.ClearAllPools(); + + using var stream = File.OpenRead(dbFile); + return Convert.ToHexString(SHA256.HashData(stream)); + } + + public static (string Path, string DbName) NewDbPath() + { + var dir = Path.Combine(Path.GetTempPath(), "tycho_store_tests"); + Directory.CreateDirectory(dir); + return (dir, $"{Guid.NewGuid()}.db"); + } + + public static (string Path, string DbName) Split(string dbFile) + => (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + public 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. + public static Tycho ReopenDb(string path, string dbName, bool persistConnection = true, bool useConnectionPooling = true) + { + SqliteConnection.ClearAllPools(); +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: useConnectionPooling); +#else + return new Tycho(path, Serializer, dbName, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: useConnectionPooling); +#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. + /// + public 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..3587fa2 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; @@ -91,12 +96,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. + /// given performance profile, honoring optional cache-size / mmap overrides. 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) + long? mmapSizeBytesOverride = null, + bool newDatabase = true) { bool desktop = profile == TychoPerformanceProfile.Desktop; @@ -105,9 +113,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 + 160); + var sb = new System.Text.StringBuilder(CreationPragma.Length + SharedPragmas.Length + SchemaDdl.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") @@ -561,10 +574,6 @@ 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;"; - public const string SelectIndexMetadata = """ SELECT PhysicalName, Definition, ShapeVersion @@ -594,6 +603,22 @@ 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. These find and delete rows left in the file, + // reloading so the open connection forgets them. The table stays, because 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 82fcfa7..62b3d2f 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; @@ -153,7 +156,9 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; - _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes); + _databasePath = databasePath; + _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, newDatabase: false); + _creationScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, newDatabase: true); } /// @@ -240,7 +245,16 @@ public Tycho Connect() return this; } - _connection = BuildConnection(); + _connectionGate.Wait(); + + try + { + _connection ??= OpenConnection(); + } + finally + { + _connectionGate.Release(); + } return this; } @@ -256,7 +270,16 @@ public async ValueTask ConnectAsync() return this; } - _connection = await BuildConnectionAsync().ConfigureAwait(false); + await _connectionGate.WaitAsync().ConfigureAwait(false); + + try + { + _connection ??= OpenConnection(); + } + finally + { + _connectionGate.Release(); + } return this; } @@ -270,7 +293,6 @@ public void Disconnect() { if (_connection is not null) { - RunOptimize(_connection); _connection.Close(); _connection.Dispose(); _connection = null; @@ -289,40 +311,12 @@ public async ValueTask DisconnectAsync() return; } - RunOptimize(_connection); - await _connection.CloseAsync().ConfigureAwait(false); await _connection.DisposeAsync().ConfigureAwait(false); _connection = null; } - /// - /// 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. - /// - /// 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. - /// - /// Best-effort: failures never block connect or teardown. - /// - private static void RunOptimize(SqliteConnection connection) - { - try - { - using var command = connection.CreateCommand(); - command.CommandText = "PRAGMA analysis_limit = 400; PRAGMA optimize;"; - command.ExecuteNonQuery(); - } - catch - { - // Advisory only — ignore failures during teardown. - } - } - public void Backup(SqliteConnection backupDatabaseConnection) { _connection?.BackupDatabase(backupDatabaseConnection); @@ -2233,7 +2227,7 @@ 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) @@ -2282,18 +2276,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. - try - { - ExecuteNonQuery(conn, Queries.AnalyzeBounded); - } - catch - { - // Statistics are an optimization, not a correctness requirement. - } - return true; } @@ -2638,6 +2620,37 @@ public IReadOnlyList ListIndexes() _persistConnection); } + /// + /// 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. Writes nothing + /// when there is nothing to delete, so a current store's connect is read-only. + /// + 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(); + } + + 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. /// @@ -2898,11 +2911,6 @@ protected virtual void Dispose(bool disposing) if (disposing) { - if (_connection is not null) - { - RunOptimize(_connection); - } - _connectionGate?.Dispose(); _connection?.Close(); _connection?.Dispose(); @@ -2959,72 +2967,77 @@ private static string ToSafeIdentifier(string derivedTypeName) return char.IsDigit(buffer[0]) ? string.Concat("_", buffer.ToString()) : buffer.ToString(); } - private SqliteConnection BuildConnection() + /// + /// Opens a connection on the file and sets it up. Runs under the gate. 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() { var connection = new SqliteConnection(_dbConnectionString); - 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 + { + InitializeConnection(connection, ConnectionScript()); - RunOptimize(conn); - }, - _persistConnection); + if (!_persistConnection) + { + connection.Close(); + } - return connection; + return connection; + } + catch + { + connection.Dispose(); + throw; + } } - private async ValueTask BuildConnectionAsync(CancellationToken cancellationToken = default) + /// + /// Opens and runs on it. The + /// statistics delete is best-effort: a store on a read-only file or a full volume + /// connects, and the planner stays misled until a connect that can write. Runs under the + /// gate. + /// + private static void InitializeConnection(SqliteConnection connection, string script) { - await _connectionGate.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - var connection = new SqliteConnection(_dbConnectionString); - - connection.Open(); + 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); + // 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). + // 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(); - - RunOptimize(connection); + command.ExecuteNonQuery(); - return connection; + try + { + RemoveLeftoverStatistics(connection); } - finally + catch (SqliteException) { - _connectionGate.Release(); } } + /// + /// 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 00ba1664e540584c6c0b8ece67411304d442ace2 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 03/11] fix: run Disconnect, Dispose and Backup under the connection gate --- TychoDB.UnitTests/ConnectionLifecycleTests.cs | 133 ++++++++++++++++++ TychoDB/Tycho.cs | 116 +++++++++------ 2 files changed, 209 insertions(+), 40 deletions(-) create mode 100644 TychoDB.UnitTests/ConnectionLifecycleTests.cs diff --git a/TychoDB.UnitTests/ConnectionLifecycleTests.cs b/TychoDB.UnitTests/ConnectionLifecycleTests.cs new file mode 100644 index 0000000..16b7673 --- /dev/null +++ b/TychoDB.UnitTests/ConnectionLifecycleTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; +using static TychoDB.UnitTests.StoreFixture; + +namespace TychoDB.UnitTests; + +/// +/// Proves Connect, Disconnect, Dispose and Backup take the +/// connection gate like every other operation: they wait for the operation in progress +/// instead of closing the connection under it, and leave no operation waiting for good. +/// +[TestClass] +public class ConnectionLifecycleTests +{ + [TestMethod] + public async Task ConcurrentConnects_OpenOneConnection() + { + var (path, dbName) = NewDbPath(); + + using var db = BuildDb(path, dbName); + + await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(db.Connect))); + + await db.WriteObjectsAsync(Items(), x => x.Key); + (await db.CountObjectsAsync()).ShouldBe(100); + } + + [TestMethod] + public async Task Disconnect_DuringOperations_LeavesAnInstanceThatReconnects() + { + const int rows = 5_000; + + var dbFile = await SeedLegacyStore(rows); + var (path, dbName) = Split(dbFile); + + using var db = await ReopenDb(path, dbName).ConnectAsync(); + + foreach (int delay in new[] { 0, 1, 2, 5, 10 }) + { + var reads = StartReads(db); + + await Task.Delay(delay); + db.Disconnect(); + + (await Task.WhenAll(reads)).ShouldAllBe(count => count == rows || count == -1); + + db.Connect(); + (await db.CountObjectsAsync()).ShouldBe(rows); + } + } + + [TestMethod] + public async Task Dispose_WithOperationsWaiting_LeavesNoneOfThemHanging() + { + const int rows = 5_000; + + var dbFile = await SeedLegacyStore(rows); + var (path, dbName) = Split(dbFile); + + foreach (int delay in new[] { 0, 1, 2, 5, 10 }) + { + var db = await ReopenDb(path, dbName).ConnectAsync(); + var reads = StartReads(db); + + await Task.Delay(delay); + db.Dispose(); + + (await Task.WhenAll(reads).WaitAsync(TimeSpan.FromSeconds(30))) + .ShouldAllBe(count => count == rows || count == -1); + } + } + + [TestMethod] + public async Task Operations_AfterDispose_ThrowObjectDisposed() + { + var (path, dbName) = NewDbPath(); + + var db = await BuildDb(path, dbName).ConnectAsync(); + db.Dispose(); + + Should.Throw(() => db.Connect()); + await Should.ThrowAsync(async () => await db.ConnectAsync()); + await Should.ThrowAsync(async () => await db.CountObjectsAsync()); + } + +#if !ENCRYPTED + [DataTestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task Backup_CopiesTheStore(bool persistConnection) + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using var db = await ReopenDb(path, dbName, persistConnection: persistConnection).ConnectAsync(); + using var destination = new SqliteConnection("Data Source=:memory:"); + destination.Open(); + + db.Backup(destination); + + using var command = destination.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM JsonValue"; + command.ExecuteScalar().ShouldBe(100L); + } +#endif + + /// + /// Reads that run to their end when they have the gate first, and fail as a call on a + /// closed instance does when they do not. + /// + private static List> StartReads(Tycho db) + => Enumerable.Range(0, 4) + .Select(_ => Task.Run(async () => + { + try + { + return (await db.ReadObjectsAsync()).Count(); + } + catch (Exception ex) when (ex is TychoException or ArgumentNullException or ObjectDisposedException) + { + return -1; + } + })) + .ToList(); +} diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 62b3d2f..c0ed5e3 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Linq.Expressions; @@ -39,7 +40,6 @@ private const string // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); - private readonly Lock _connectionLock = new(); private readonly string _dbConnectionString; // Per-connection setup scripts (profile PRAGMAs + schema DDL), built once: one for @@ -80,7 +80,11 @@ private const string // lighter than a rate limiter for this "one operation at a time" gate and, // unlike the previous AttemptAcquire path (which ignored whether a permit was // actually obtained), its synchronous Wait genuinely serializes sync callers. + // Never disposed: an operation waiting on a disposed SemaphoreSlim is never woken, and + // Dispose cannot know who is waiting. Without AvailableWaitHandle it holds nothing to free. +#pragma warning disable CA2213 private readonly SemaphoreSlim _connectionGate = new(1, 1); +#pragma warning restore CA2213 private SqliteConnection? _connection; private bool _isDisposed; @@ -285,41 +289,63 @@ public async ValueTask ConnectAsync() } /// - /// Closes the current database connection. + /// Closes the current database connection, once the operation in progress has finished. /// public void Disconnect() { - lock (_connectionLock) + _connectionGate.Wait(); + + try { - if (_connection is not null) - { - _connection.Close(); - _connection.Dispose(); - _connection = null; - } + CloseConnection(); + } + finally + { + _connectionGate.Release(); } } /// - /// Asynchronously closes the current database connection. + /// Asynchronously closes the current database connection, once the operation in + /// progress has finished. /// /// A ValueTask representing the asynchronous operation. public async ValueTask DisconnectAsync() { - if (_connection is null) + await _connectionGate.WaitAsync().ConfigureAwait(false); + + try { - return; + CloseConnection(); } + finally + { + _connectionGate.Release(); + } + } - await _connection.CloseAsync().ConfigureAwait(false); - await _connection.DisposeAsync().ConfigureAwait(false); + [MemberNotNull(nameof(_connection))] + private void EnsureConnected() + { + ObjectDisposedException.ThrowIf(_isDisposed, this); + ArgumentNullException.ThrowIfNull(_connection); + } + /// Closes the connection. Runs under the gate. + private void CloseConnection() + { + _connection?.Close(); + _connection?.Dispose(); _connection = null; } public void Backup(SqliteConnection backupDatabaseConnection) { - _connection?.BackupDatabase(backupDatabaseConnection); + _connection?.WithConnectionBlock( + _connectionGate, + backupDatabaseConnection, + static (conn, destination) => conn.BackupDatabase(destination), + _persistConnection); } /// @@ -411,7 +437,7 @@ public ValueTask WriteObjectsAsync(IEnumerable objs, Func { ArgumentNullException.ThrowIfNull(objs); ArgumentNullException.ThrowIfNull(keySelector); - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); keySelector = GuardAgainstKeyDivergence(keySelector); @@ -612,7 +638,7 @@ public ValueTask UpsertObjectAsync(T obj, Func keySe { ArgumentNullException.ThrowIfNull(obj); ArgumentNullException.ThrowIfNull(keySelector); - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); keySelector = GuardAgainstKeyDivergence(keySelector); @@ -729,7 +755,7 @@ public ValueTask CountObjectsAsync(string? partition = null, FilterBuild CheckHasRegisteredType(); } - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -820,7 +846,7 @@ public ValueTask ObjectExistsAsync(object key, string? partition = null CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(key); - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -906,7 +932,7 @@ public ValueTask ReadObjectAsync(object key, string? partition = null, boo IProgress? progress = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(key); - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1153,7 +1179,7 @@ private ValueTask> ReadObjectsCoreAsync( CheckHasRegisteredType(); } - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync, (string? partition, FilterBuilder? filter, SortBuilder? sort, int? top, bool withTransaction, IProgress? progress, StringBuilder commandBuilder, int commandTimeout, IJsonSerializer jsonSerializer, string? keysJson, KeyColumnRewrite? keyRewrite, CancellationToken cancellationToken)>( @@ -1438,7 +1464,7 @@ await ReadObjectsWithKeysAsync(innerObjectSelection, partition, filter, withTran CheckHasRegisteredType(); } - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); string selectionPath = QueryPropertyPath.BuildPath(innerObjectSelection, NameResolver); @@ -1559,7 +1585,7 @@ public ValueTask DeleteObjectWithKeyAsync(object key, string? partition CheckHasRegisteredType(); } - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1626,7 +1652,7 @@ public ValueTask DeleteObjectsAsync(string? partition = null, FilterBuil CheckHasRegisteredType(); } - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1696,7 +1722,7 @@ public ValueTask DeleteObjectsAsync(string? partition = null, FilterBuil public ValueTask DeleteObjectsAsync(string partition, bool withTransaction = true, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1752,7 +1778,7 @@ public ValueTask DeleteObjectsAsync(string partition, bool withTransaction /// A ValueTask containing the count of deleted objects. public ValueTask DeleteObjectsAsync(bool withTransaction = true, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1809,7 +1835,7 @@ public ValueTask DeleteObjectsAsync(bool withTransaction = true, Cancellati public ValueTask WriteBlobAsync(Stream stream, object key, string? partition = null, bool withTransaction = true, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1877,7 +1903,7 @@ static async (conn, state) => public ValueTask BlobExistsAsync(object key, string? partition = null, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1929,7 +1955,7 @@ public ValueTask BlobExistsAsync(object key, string? partition = null, public ValueTask ReadBlobAsync(object key, string? partition = null, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -1982,7 +2008,7 @@ public ValueTask ReadBlobAsync(object key, string? partition = null, public ValueTask DeleteBlobAsync(object key, string? partition = null, bool withTransaction = true, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -2041,7 +2067,7 @@ public ValueTask DeleteBlobAsync(object key, string? partition = null, boo public ValueTask<(bool Successful, int Count)> DeleteBlobsAsync(string partition, bool withTransaction = true, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlockAsync( @@ -2339,7 +2365,7 @@ private Tycho CreateIndexCore( string? fullTypeName = null, string pathParamName = "propertyPaths") { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); var definition = BuildIndexDefinition( indexName, @@ -2365,7 +2391,7 @@ private ValueTask CreateIndexCoreAsync( string? fullTypeName = null, string pathParamName = "propertyPaths") { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); var definition = BuildIndexDefinition( indexName, @@ -2506,7 +2532,7 @@ public ValueTask CreateIndexAsync(Expression>[] p /// True if an index was dropped; false if no such index was recorded. public bool DropIndex(string indexName) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); QueryPropertyPath.ValidateIdentifier(indexName, nameof(indexName)); return _connection @@ -2526,7 +2552,7 @@ public bool DropIndex(string indexName) /// True if an index was dropped; false if no such index was recorded. public ValueTask DropIndexAsync(string indexName, CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); QueryPropertyPath.ValidateIdentifier(indexName, nameof(indexName)); return _connection @@ -2592,7 +2618,7 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st /// The recorded indexes, ordered by type then index name. public IReadOnlyList ListIndexes() { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); return _connection .WithConnectionBlock, object?>( @@ -2665,7 +2691,7 @@ private static long ReadPragma(SqliteConnection conn, string pragma) /// public void Cleanup(bool shrinkMemory = true, bool vacuum = false) { - ArgumentNullException.ThrowIfNull(_connection); + EnsureConnected(); _connection .WithConnectionBlock( @@ -2911,9 +2937,17 @@ protected virtual void Dispose(bool disposing) if (disposing) { - _connectionGate?.Dispose(); - _connection?.Close(); - _connection?.Dispose(); + _connectionGate.Wait(); + + try + { + _isDisposed = true; + CloseConnection(); + } + finally + { + _connectionGate.Release(); + } } _isDisposed = true; @@ -2974,6 +3008,8 @@ private static string ToSafeIdentifier(string derivedTypeName) /// private SqliteConnection OpenConnection() { + ObjectDisposedException.ThrowIf(_isDisposed, this); + var connection = new SqliteConnection(_dbConnectionString); try From a0dcf175a55a43104339fa66964906d1c2ffe7b1 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 04/11] fix: replace an index of another shape and the index a 4.x rollback leaves --- TychoDB.UnitTests/IndexMigrationTests.cs | 208 +++++++++++++++++++++++ TychoDB/Queries.cs | 21 ++- TychoDB/Tycho.cs | 182 +++++++++++--------- 3 files changed, 332 insertions(+), 79 deletions(-) create mode 100644 TychoDB.UnitTests/IndexMigrationTests.cs diff --git a/TychoDB.UnitTests/IndexMigrationTests.cs b/TychoDB.UnitTests/IndexMigrationTests.cs new file mode 100644 index 0000000..d174949 --- /dev/null +++ b/TychoDB.UnitTests/IndexMigrationTests.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; +using static TychoDB.UnitTests.StoreFixture; + +namespace TychoDB.UnitTests; + +/// +/// Proves a declaration replaces the index an earlier release left in its place: the string +/// overload's same-named 4.x index is recognised as stale instead of kept, and the index a +/// 4.x rollback leaves next to a current one is dropped, while one another declaration +/// records as its own is kept. +/// +[TestClass] +public class IndexMigrationTests +{ + [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); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[current.PhysicalName].ShouldBe(currentSql); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(current); + } + + [TestMethod] + public async Task StringOverload_SameNamedLegacyIndex_IsRebuilt() + { + 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)); + + using (var db = await ReopenDb(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); + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.IndexName.ShouldBe(ManualIndexName); + row.FullTypeName.ShouldBe("Item"); + row.PhysicalName.ShouldBe(ManualPhysicalName); + row.ShapeVersion.ShouldBe(2); + + // A row that says current over an index of another shape is rebuilt all the same. + Execute(dbFile, $"DROP INDEX {ManualPhysicalName}; " + LegacyIndexDdl(ManualPhysicalName)); + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + + using (var db = await ReopenDb(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 IndexNameChangedOnlyInCase_IsTheSameIndex_AndSettles() + { + 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); + } + + // SQLite compares index names without regard to case, so CREATE INDEX IF NOT EXISTS + // would keep this one, shape and all, under the name declared below. + Execute(dbFile, LegacyIndexDdl(ManualPhysicalName)); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", "MANUAL_IDX"); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile) + .Single(index => index.Key.Equals(ManualPhysicalName, StringComparison.OrdinalIgnoreCase)) + .Value + .ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + + var hash = FileHash(dbFile); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", "MANUAL_IDX"); + } + + 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"); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", IndexName); + 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 ReopenDb(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); + } + + [TestMethod] + public async Task Declaration_OverAWholeDocumentIndex_IsBuilt() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + // What 4.x built for a value-type property: the boxed path indexed the document. + Execute(dbFile, $"DROP INDEX {LegacyIndexName}; CREATE INDEX {LegacyIndexName} ON JsonValue(FullTypeName, JSON_EXTRACT(Data, '$'));"); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + ReadIndexDdl(dbFile).ShouldNotContainKey(LegacyIndexName); + ExplainLookup(dbFile).ShouldContain(row.PhysicalName, Case.Sensitive); + } +} diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 3587fa2..b709396 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -600,8 +600,25 @@ FROM TychoIndex ORDER BY FullTypeName, IndexName; """; - public const string SelectPhysicalIndexExists = - "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + // SQLite index names are case-insensitive, so these compare them that way. + public const string SelectIndexRecordedByAnother = + """ + SELECT 1 + FROM TychoIndex + WHERE PhysicalName = $physicalName COLLATE NOCASE + AND NOT (IndexName = $indexName AND FullTypeName = $fullTypeName); + """; + + public const string SelectIndexSql = + "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = $physicalName COLLATE NOCASE;"; + + /// + /// 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(';')); // Planner statistics. TychoDB gathers none: SQLite's default heuristics choose the // right index for every query it emits. These find and delete rows left in the file, diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index c0ed5e3..8e3e100 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -2248,12 +2248,20 @@ 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 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. + /// 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. + /// + /// + /// An 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 not this + /// declaration's to drop. /// /// private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) @@ -2262,100 +2270,127 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de try { - if (IsIndexCurrent(conn, definition)) + var recorded = ReadRecordedIndex(conn, definition.IndexName, definition.MetadataTypeName); + string? physicalSql = ReadIndexSql(conn, definition.PhysicalName); + bool hasLegacyName = !string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal); + string? legacySql = hasLegacyName ? ReadIndexSql(conn, definition.LegacyPhysicalName) : null; + bool legacyOrphan = legacySql is not null + && !IsRecordedByAnotherIndex(conn, definition.LegacyPhysicalName, definition.IndexName, definition.MetadataTypeName); + + if (string.Equals(physicalSql, Queries.StoredIndexSql(definition.CommandText), StringComparison.Ordinal)) { + if (!IsRecorded(recorded, definition)) + { + UpsertIndexMetadata(conn, definition); + } + + if (legacyOrphan) + { + 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 (recorded is { } stale && !string.Equals(stale.PhysicalName, definition.PhysicalName, StringComparison.Ordinal)) { - ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); + ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stale.PhysicalName))); } - if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) + if (physicalSql is not null) { - ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + ExecuteNonQuery(conn, Queries.DropIndex(definition.PhysicalName)); } - ExecuteNonQuery(conn, definition.CommandText); - - using (var upsert = conn.CreateCommand()) + if (legacyOrphan) { - 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); + transaction.Commit(); + return true; } catch (Exception ex) { transaction.Rollback(); throw new TychoException($"Failed to Create Index: {definition.PhysicalName}", ex); } - - 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 PhysicalName, string Definition, long ShapeVersion); + + private static IndexMetadataRow? ReadRecordedIndex(SqliteConnection conn, string indexName, string typeName) { 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 }); + lookup.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = indexName }); + lookup.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = typeName }); - string? recordedDefinition = null; - long recordedVersion = -1; + using var reader = lookup.ExecuteReader(); - using (var reader = lookup.ExecuteReader()) - { - if (reader.Read()) - { - recordedDefinition = reader.GetString(1); - recordedVersion = reader.GetInt64(2); - } - } + return reader.Read() + ? new IndexMetadataRow(reader.GetString(0), reader.GetString(1), reader.GetInt64(2)) + : null; + } - if (recordedVersion != IndexShapeVersion || - !string.Equals(recordedDefinition, definition.CommandText, StringComparison.Ordinal)) - { - return false; - } + private static bool IsRecorded(IndexMetadataRow? recorded, IndexDefinition definition) + => recorded is { } row + && row.ShapeVersion == IndexShapeVersion + && string.Equals(row.Definition, definition.CommandText, StringComparison.Ordinal); - using var exists = conn.CreateCommand(); - exists.CommandText = Queries.SelectPhysicalIndexExists; - exists.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); - return exists.ExecuteScalar() is not null; + /// 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 List ReadRecordedPhysicalNames(SqliteConnection conn, IndexDefinition definition) + /// + /// 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) { - var names = new List(1); - 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 }); + 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; + } - using var reader = lookup.ExecuteReader(); - while (reader.Read()) - { - names.Add(reader.GetString(0)); - } + private static void UpsertIndexMetadata(SqliteConnection conn, IndexDefinition definition) + { + 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(); + } - return names; + /// + /// 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 physicalName.Length > suffix.Length && physicalName.EndsWith(suffix, StringComparison.Ordinal) + ? physicalName[..^suffix.Length] + : null; } private Tycho CreateIndexCore( @@ -2570,20 +2605,7 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st try { - string? physicalName = null; - - using (var lookup = conn.CreateCommand()) - { - lookup.CommandText = Queries.SelectIndexMetadata; - lookup.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = indexName }); - lookup.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = typeName }); - - using var reader = lookup.ExecuteReader(); - if (reader.Read()) - { - physicalName = reader.GetString(0); - } - } + string? physicalName = ReadRecordedIndex(conn, indexName, typeName)?.PhysicalName; if (physicalName is null) { @@ -2593,6 +2615,12 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(physicalName))); + if (LegacyPhysicalNameOf(physicalName, typeName) is { } legacyName + && !IsRecordedByAnotherIndex(conn, legacyName, indexName, typeName)) + { + ExecuteNonQuery(conn, Queries.DropIndex(legacyName)); + } + using (var delete = conn.CreateCommand()) { delete.CommandText = Queries.DeleteIndexMetadata; From 9b0a9d062383ff6a99e1e561c8edcae73a239b85 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 05/11] fix: compact a store with VACUUM INTO and a file swap instead of a full VACUUM --- TychoDB.UnitTests/CompactionTests.cs | 310 ++++++++++++++++++++++++ TychoDB/Queries.cs | 38 +++ TychoDB/Tycho.cs | 349 ++++++++++++++++++++++----- 3 files changed, 641 insertions(+), 56 deletions(-) create mode 100644 TychoDB.UnitTests/CompactionTests.cs diff --git a/TychoDB.UnitTests/CompactionTests.cs b/TychoDB.UnitTests/CompactionTests.cs new file mode 100644 index 0000000..51caad5 --- /dev/null +++ b/TychoDB.UnitTests/CompactionTests.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; +using static TychoDB.UnitTests.StoreFixture; + +namespace TychoDB.UnitTests; + +/// +/// Proves the compaction of a store without incremental auto-vacuum: the instance keeps +/// serving on the swapped-in file, operations waiting on the gate survive it, a copy that +/// cannot be written leaves the store in use, an interrupted run's leftover goes at connect, +/// the file's permissions and a symbolic link survive, and it is skipped while another +/// connection has the file. +/// +[TestClass] +public class CompactionTests +{ + [TestMethod] + public async Task Cleanup_SwapsInTheCompactedCopy_AndKeepsServingOnIt() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + db.Cleanup(shrinkMemory: true, vacuum: true); + + // 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(dbFile + Queries.CompactedFileSuffix).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); + + // Reopened from scratch, the store is the compacted one. + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(101); + } + } + + [DataTestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task Cleanup_WithoutAPersistentConnection_Compacts(bool useConnectionPooling) + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, persistConnection: false, useConnectionPooling: useConnectionPooling).ConnectAsync()) + { + db.Cleanup(shrinkMemory: false, vacuum: true); + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(100); + } + + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [DataTestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task OperationsDuringACompaction_AllSucceed_AndNothingIsLost(bool persistConnection) + { + const int rows = 20_000; + + var dbFile = await SeedLegacyStore(rows); + var (path, dbName) = Split(dbFile); + int writes = 0; + int reads = 0; + + using (var db = await ReopenDb(path, dbName, persistConnection: persistConnection).ConnectAsync()) + { + var compaction = Task.Run(() => db.Cleanup(shrinkMemory: false, vacuum: true)); + + var readers = Enumerable.Range(0, 3).Select(_ => Task.Run(async () => + { + do + { + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBeGreaterThanOrEqualTo(rows); + Interlocked.Increment(ref reads); + } + while (!compaction.IsCompleted); + })); + + var writer = Task.Run(async () => + { + do + { + await db.WriteObjectAsync(new Item { Key = $"written-{writes}", Group = "G0", Seq = rows + writes }, x => x.Key); + writes++; + } + while (!compaction.IsCompleted); + }); + + await compaction; + await Task.WhenAll(readers.Append(writer)); + + reads.ShouldBeGreaterThan(0); + (await db.CountObjectsAsync()).ShouldBe(rows + writes); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadScalar(dbFile, "SELECT COUNT(*) FROM JsonValue").ShouldBe(rows + writes); + ReadText(dbFile, "PRAGMA integrity_check").ShouldBe("ok"); + } + + [TestMethod] + public async Task Cleanup_WhenTheCopyCannotBeWritten_ThrowsAndKeepsServing() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + var compactedFile = dbFile + Queries.CompactedFileSuffix; + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + // A directory in the way can be neither deleted as a file nor written over. + Directory.CreateDirectory(compactedFile); + + Should.Throw(() => db.Cleanup(shrinkMemory: false, vacuum: true)); + await AssertLookup(db); + await db.WriteObjectAsync(new Item { Key = "item-new", Group = "G0", Seq = 1000 }, x => x.Key); + + Directory.Delete(compactedFile); + + db.Cleanup(shrinkMemory: false, vacuum: true); + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(101); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [TestMethod] + public async Task Cleanup_WhileABlobStreamIsOpen_LeavesTheStoreAsItWas() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + using (var blob = new MemoryStream(new byte[4096])) + { + await db.WriteBlobAsync(blob, "blob-1"); + } + + var stream = await db.ReadBlobAsync("blob-1"); + + // SQLite refuses to run VACUUM INTO under an open blob, before anything changes. + db.Cleanup(shrinkMemory: false, vacuum: true); + await AssertLookup(db); + stream.ReadByte().ShouldBe(0); + + await stream.DisposeAsync(); + + db.Cleanup(shrinkMemory: false, vacuum: true); + await AssertLookup(db); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [TestMethod] + public async Task Cleanup_OfAStoreInFullAutoVacuum_ConvertsIt() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + Execute(dbFile, "PRAGMA auto_vacuum = FULL; CREATE TABLE Bootstrap(Id INTEGER); DROP TABLE Bootstrap;"); + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(1); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + + db.Cleanup(shrinkMemory: false, vacuum: true); + + (await db.CountObjectsAsync()).ShouldBe(100); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task Connect_DeletesTheCopyAnInterruptedCompactionLeft(bool rebuildCache) + { + // A store with incremental auto-vacuum never compacts again, so nothing else would. + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + var compactedFile = dbFile + Queries.CompactedFileSuffix; + + using (await BuildDb(path, dbName).ConnectAsync()) + { + } + + File.WriteAllText(compactedFile, "not a database"); + File.WriteAllText(compactedFile + "-journal", "not a journal"); + + SqliteConnection.ClearAllPools(); + + using (await (rebuildCache ? BuildDb(path, dbName) : ReopenDb(path, dbName)).ConnectAsync()) + { + } + + File.Exists(compactedFile).ShouldBeFalse(); + File.Exists(compactedFile + "-journal").ShouldBeFalse(); + } + + [TestMethod] + public async Task Compaction_KeepsTheFilePermissions() + { + if (OperatingSystem.IsWindows()) + { + Assert.Inconclusive("Unix file modes do not exist on Windows."); + } + + const UnixFileMode ownerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; + + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + SqliteConnection.ClearAllPools(); + File.SetUnixFileMode(dbFile, ownerOnly); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + db.Cleanup(shrinkMemory: false, vacuum: true); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + File.GetUnixFileMode(dbFile).ShouldBe(ownerOnly); + } + + [TestMethod] + public async Task Compaction_OfALinkedStore_ReplacesTheFileAndKeepsTheLink() + { + if (OperatingSystem.IsWindows()) + { + Assert.Inconclusive("Creating a symbolic link needs a privilege on Windows."); + } + + var dbFile = await SeedLegacyStore(); + var (path, _) = Split(dbFile); + var linkName = $"{Guid.NewGuid()}.db"; + var linkFile = Path.Combine(path, linkName); + + File.CreateSymbolicLink(linkFile, dbFile); + + using (var db = await ReopenDb(path, linkName).ConnectAsync()) + { + db.Cleanup(shrinkMemory: false, vacuum: true); + await AssertLookup(db); + } + + new FileInfo(linkFile).LinkTarget.ShouldBe(dbFile); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + File.Exists(linkFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + } + + [TestMethod] + public async Task Compaction_WhileAnotherConnectionHasTheFile_IsSkipped() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using var db = await ReopenDb(path, dbName, persistConnection: false, useConnectionPooling: false).ConnectAsync(); + + using (var other = OpenInspection(dbFile)) + { + using var command = other.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM JsonValue"; + command.ExecuteScalar().ShouldBe(100L); + + db.Cleanup(shrinkMemory: false, vacuum: true); + + await db.WriteObjectAsync(new Item { Key = "item-new", Group = "G0", Seq = 1000 }, x => x.Key); + command.ExecuteScalar().ShouldBe(101L); + + command.CommandText = "PRAGMA auto_vacuum"; + command.ExecuteScalar().ShouldBe(0L); + } + + SqliteConnection.ClearAllPools(); + + db.Cleanup(shrinkMemory: false, vacuum: true); + (await db.CountObjectsAsync()).ShouldBe(101); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } +} diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index b709396..2adc21b 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -636,6 +636,44 @@ public static string StoredIndexSql(string createIndexStatement) 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;"; + + 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 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 = "-tycho-compact"; + + // What SQLite says, under the generic SQLITE_ERROR, when a statement or blob stream of the + // connection is still open. + public const string StatementsInProgress = "SQL statements in progress"; + + // Taking this lock stops the swap when another connection holds a lock on the file. A + // persistent connection already holds it; a connection opened per operation may not. Two + // commands, because Microsoft.Data.Sqlite swallows an error raised after a statement + // that returns a row, as the pragma does. + public const string ExclusiveLockingMode = "PRAGMA locking_mode = EXCLUSIVE;"; + + public const string AcquireExclusiveLock = "BEGIN IMMEDIATE; COMMIT;"; + // 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 8e3e100..50312a8 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -37,6 +37,17 @@ private const string /// private const int IndexShapeVersion = 2; + // SQLite result codes for the failures maintenance leaves for a later call instead of + // raising: another connection holds the file, a statement or blob stream of this + // connection is still open, and the volume has no room for a write. + private const int SqliteBusy = 5; + private const int SqliteLocked = 6; + private const int SqliteFull = 13; + + // How long a maintenance step retries those first two, in seconds. The default command + // timeout would hold the gate for 30 s, with every other operation waiting behind it. + private const int MaintenanceBusyTimeout = 1; + // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); @@ -2674,6 +2685,254 @@ public IReadOnlyList ListIndexes() _persistConnection); } + /// + /// Runs maintenance under the gate, on the connection as it is now. A disconnected + /// instance ends the work, and a full volume or a file in use leaves it for a later call; + /// neither is a failure. + /// + private bool RunMaintenanceStep(Func step) + { + var connection = _connection; + + if (connection is null) + { + return false; + } + + int defaultTimeout = connection.DefaultTimeout; + + try + { + connection.DefaultTimeout = MaintenanceBusyTimeout; + + if (!_persistConnection) + { + connection.Open(); + } + + return step(connection); + } + catch (Exception ex) when (_connection is not null && CanWaitForALaterCall(ex)) + { + return false; + } + catch (Exception ex) when (ex is not TychoException) + { + throw new TychoException("Failed to optimize database", ex); + } + finally + { + connection.DefaultTimeout = defaultTimeout; + + if (!_persistConnection) + { + connection.Close(); + } + } + } + + private static bool CanWaitForALaterCall(Exception ex) + => (ex as SqliteException ?? ex.InnerException as SqliteException) is { } sqliteException + && (sqliteException.SqliteErrorCode is SqliteBusy or SqliteLocked or SqliteFull + || sqliteException.Message.Contains(Queries.StatementsInProgress, StringComparison.Ordinal)); + + /// + /// 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 — is converted by + /// . Later calls reclaim in place. + /// + private bool ReclaimFreePages(SqliteConnection conn) + { + if (ReadPragma(conn, Queries.AutoVacuumMode) != 2) + { + return CompactStore(conn); + } + + ExecuteNonQuery(conn, Queries.IncrementalVacuum); + + return true; + } + + /// + /// 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. + /// 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 copy is flushed to disk, since the SQLite of the SQLCipher build writes it without + /// syncing, and takes the file's permissions. The connection then closes, which + /// checkpoints the WAL into the file; the -wal and -shm files are deleted; + /// the copy is renamed over the database; and the same connection object reopens on it, + /// so operations already waiting on the gate with that object run on the new file. + /// + /// 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. 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, so the copy is discarded. 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 connect removes. + /// + /// + /// The swap replaces the file, so attributes set on the old one other than its + /// permissions — a backup exclusion, a file protection class — do not carry over. + /// Skipped, to be retried by the next call, when the volume lacks the space, SQLite + /// reports it full, another connection holds a lock on the file, or such a WAL remains. + /// A connection that has the file open and holds no lock, as one retrying a busy file + /// does, cannot be seen: it would go on with the replaced file and the -wal of the + /// new one, which is why a store takes one instance. Runs under the gate. + /// + /// + /// True when the store was swapped; false when the compaction was skipped. + private bool CompactStore(SqliteConnection connection) + { + string databasePath = ResolvedDatabasePath(); + string compactedPath = databasePath + Queries.CompactedFileSuffix; + + DeleteCompactedCopy(); + + long liveBytes = + (ReadPragma(connection, Queries.PageCount) - ReadPragma(connection, Queries.FreelistCount)) + * ReadPragma(connection, Queries.PageSize); + + if (!HasFreeSpaceFor(databasePath, liveBytes)) + { + return false; + } + + try + { + ExecuteNonQuery(connection, Queries.ExclusiveLockingMode); + ExecuteNonQuery(connection, Queries.AcquireExclusiveLock); + 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(); + } + + CopyFileMode(databasePath, compactedPath); + + using var copy = new FileStream(compactedPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + copy.Flush(flushToDisk: true); + } + catch + { + DeleteCompactedCopy(); + throw; + } + + connection.Close(); + SqliteConnection.ClearPool(connection); + + bool swapped = false; + Exception? swapFailure = null; + + try + { + string walPath = databasePath + "-wal"; + + if (new FileInfo(walPath) is not { Exists: true, Length: > 0 }) + { + File.Delete(walPath); + File.Delete(databasePath + "-shm"); + File.Move(compactedPath, databasePath, overwrite: true); + swapped = true; + } + } + catch (Exception ex) + { + swapFailure = ex; + } + + if (!swapped) + { + DeleteCompactedCopy(); + } + + try + { + InitializeConnection(connection, _connectionScript); + } + catch (Exception ex) + { + CloseConnection(); + throw new TychoException("Failed to reopen the database after compacting it; call Connect to retry", swapFailure ?? ex); + } + + return swapFailure is null + ? swapped + : throw new TychoException("Failed to compact database", swapFailure); + } + + /// + /// Gives the permissions of . + /// Best-effort: a volume without Unix permissions refuses, and has none to keep. + /// + private static void CopyFileMode(string source, string destination) + { + if (OperatingSystem.IsWindows()) + { + return; + } + + try + { + File.SetUnixFileMode(destination, File.GetUnixFileMode(source)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + /// + /// The file SQLite has open: it follows a symbolic link, and keeps the -wal and + /// -shm files next to the file the link points at. + /// + private string ResolvedDatabasePath() + => (File.Exists(_databasePath) ? File.ResolveLinkTarget(_databasePath, returnFinalTarget: true)?.FullName : null) + ?? _databasePath; + + /// + /// Deletes the copy an interrupted compaction left, which SQLite would refuse to write + /// over, and its journal. Best-effort: nothing depends on this having worked. + /// + private void DeleteCompactedCopy() + { + try + { + string compactedPath = ResolvedDatabasePath() + Queries.CompactedFileSuffix; + + File.Delete(compactedPath); + File.Delete(compactedPath + "-journal"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + /// + /// Whether the volume holding 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 static bool HasFreeSpaceFor(string filePath, long bytes) + { + try + { + string fullPath = Path.GetFullPath(filePath); + 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; + } + } + /// /// 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 @@ -2714,71 +2973,47 @@ 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) { EnsureConnected(); - _connection - .WithConnectionBlock( - _connectionGate, - (shrinkMemory, vacuum), - static (conn, state) => - { - try + if (shrinkMemory) + { + _connection + .WithConnectionBlock( + _connectionGate, + static conn => { - if (state.shrinkMemory) - { - using var shrinkCommand = conn.CreateCommand(); - shrinkCommand.CommandText = "PRAGMA shrink_memory;"; - shrinkCommand.ExecuteNonQuery(); - } - - if (!state.vacuum) + try { - return; + ExecuteNonQuery(conn, Queries.ShrinkMemory); } - - // incremental_vacuum only reclaims space when the database is in - // INCREMENTAL (2) auto-vacuum mode. - long autoVacuumMode; - using (var modeCommand = conn.CreateCommand()) + catch (Exception ex) { - modeCommand.CommandText = "PRAGMA auto_vacuum;"; - autoVacuumMode = modeCommand.ExecuteScalar() is long mode ? mode : 0L; + throw new TychoException("Failed to clean up database", ex); } + }, + _persistConnection); + } - 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);"; - } + if (vacuum) + { + _connectionGate.Wait(); - vacuumCommand.ExecuteNonQuery(); - } - catch (Exception ex) - { - throw new TychoException("Failed to clean up database", ex); - } - }, - _persistConnection); + try + { + RunMaintenanceStep(ReclaimFreePages); + } + finally + { + _connectionGate.Release(); + } + } } /// @@ -3030,9 +3265,10 @@ private static string ToSafeIdentifier(string derivedTypeName) } /// - /// Opens a connection on the file and sets it up. Runs under the gate. A connection whose - /// setup fails is disposed before the failure propagates, so it does not keep the file's - /// lock until the finalizer runs. + /// Opens a connection on the file and sets it up, removing the copy an interrupted + /// compaction left. Runs under the gate. 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() { @@ -3043,6 +3279,7 @@ private SqliteConnection OpenConnection() try { InitializeConnection(connection, ConnectionScript()); + DeleteCompactedCopy(); if (!_persistConnection) { From 5ef63fcd85492fc441d28c8feef139948611046b Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 06/11] feat: add autoOptimize and Optimize to do the one-time upgrade work off the calling thread --- TychoDB.UnitTests/IndexDdlTests.cs | 50 +- TychoDB.UnitTests/OptimizeTests.cs | 859 ++++++++++++++++++++ TychoDB.UnitTests/PlannerStatisticsTests.cs | 40 +- TychoDB.UnitTests/StoreFixture.cs | 6 +- TychoDB/Queries.cs | 68 +- TychoDB/Tycho.cs | 337 +++++++- 6 files changed, 1285 insertions(+), 75 deletions(-) create mode 100644 TychoDB.UnitTests/OptimizeTests.cs diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 3513b30..3be1774 100644 --- a/TychoDB.UnitTests/IndexDdlTests.cs +++ b/TychoDB.UnitTests/IndexDdlTests.cs @@ -508,6 +508,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() { @@ -712,13 +756,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/OptimizeTests.cs b/TychoDB.UnitTests/OptimizeTests.cs new file mode 100644 index 0000000..4a9457d --- /dev/null +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -0,0 +1,859 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Linq.Expressions; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; +using static TychoDB.UnitTests.StoreFixture; + +namespace TychoDB.UnitTests; + +/// +/// Proves the deferred upgrade path and the work Optimize does: under +/// autoOptimize: false a declaration the index 4.x built can serve is left to +/// Optimize, with nothing written, and one no index serves is built at once; a current +/// store is never written to by connect, by a declaration, or by Optimize; and every +/// operation keeps working during Optimize and runs between its steps. +/// +[TestClass] +public class OptimizeTests +{ + [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 ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + // Nothing written: no DDL ran, no row was recorded, the 4.x index 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"); + ReadMetadata(dbFile).ShouldBeEmpty(); + + 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 ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.ListIndexes().ShouldBeEmpty(); + db.Optimize().ShouldBeTrue(); + db.ListIndexes().ShouldHaveSingleItem().IndexName.ShouldBe(IndexName); + await AssertLookup(db); + } + + var built = ReadMetadata(dbFile).ShouldHaveSingleItem(); + built.IndexName.ShouldBe(IndexName); + built.FullTypeName.ShouldBe(typeof(Item).FullName); + built.PhysicalName.ShouldStartWith(LegacyIndexName + "_"); + built.ShapeVersion.ShouldBe(2); + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[built.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + ddl.ShouldContainKey(GeneralIndexName); + + foreach (var name in BuiltInLegacyIndexNames) + { + ddl.ShouldNotContainKey(name); + } + + ExplainLookup(dbFile).ShouldContain(built.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 ReopenDb(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 ReopenDb(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 ReopenDb(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_WithAutoOptimizeOff_LeavesTheOrphanToOptimize() + { + 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)); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize().ShouldBeTrue(); + await AssertLookup(db); + } + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[current.PhysicalName].ShouldBe(currentSql); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(current); + } + + [TestMethod] + public async Task StringOverload_WithAutoOptimizeOff_LeavesTheRebuildToOptimize() + { + 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)); + + using (var db = await ReopenDb(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); + ReadMetadata(dbFile).ShouldBeEmpty(); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", ManualIndexName); + db.Optimize().ShouldBeTrue(); + 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 ReopenDb(path, dbName, autoOptimize: 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 LegacyStore_Optimize_CompactsAndKeepsServing() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize().ShouldBeTrue(); + + await AssertLookup(db); + await db.WriteObjectAsync(new Item { Key = "item-new", Group = "G0", Seq = 1000 }, x => x.Key); + (await db.CountObjectsAsync()).ShouldBe(101); + } + + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + + [TestMethod] + public async Task LegacyStore_Optimize_WithoutAPersistentConnection_Compacts() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, persistConnection: false, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize().ShouldBeTrue(); + 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 Compaction_WhileAnotherConnectionHasTheFile_ReturnsFalse() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using var db = await ReopenDb(path, dbName, persistConnection: false, useConnectionPooling: false, autoOptimize: false).ConnectAsync(); + + using (var other = OpenInspection(dbFile)) + { + using var command = other.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM JsonValue"; + command.ExecuteScalar().ShouldBe(100L); + + db.Optimize().ShouldBeFalse(); + } + + SqliteConnection.ClearAllPools(); + + db.Optimize().ShouldBeTrue(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [TestMethod] + public async Task LegacyStore_Cleanup_DoesTheDeferredWorkBeforeCompacting() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Cleanup(shrinkMemory: false, vacuum: true); + await AssertLookup(db); + } + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl.ShouldContainKey(ReadMetadata(dbFile).ShouldHaveSingleItem().PhysicalName); + + foreach (var name in BuiltInLegacyIndexNames) + { + ddl.ShouldNotContainKey(name); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + } + + [TestMethod] + public async Task Declaration_TheOldIndexDoesNotServe_IsBuiltAtOnce() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + // The 4.x index under this name covers Seq; the declaration has moved to Group. + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Group, IndexName); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[row.PhysicalName].ShouldContain("$.Group", Case.Sensitive); + } + + [TestMethod] + public async Task StringOverload_ChangedProperty_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); + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", ManualIndexName); + } + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync("$.Group", isNumeric: false, "Item", ManualIndexName); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("$.Group", Case.Sensitive); + ReadMetadata(dbFile).ShouldHaveSingleItem().Definition.ShouldContain("$.Group", Case.Sensitive); + } + + [TestMethod] + public async Task BothOverloads_OnDifferentProperties_AreBothBuiltAtOnce() + { + 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); + } + + // The string overload's index sits under the generic overload's legacy name, but + // it is not an index an earlier release built for the generic declaration. + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync("$.Group", isNumeric: false, "Item", IndexName); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var rows = ReadMetadata(dbFile); + rows.Count.ShouldBe(2); + + var ddl = ReadIndexDdl(dbFile); + ddl[LegacyIndexName].ShouldContain("$.Group", Case.Sensitive); + ddl[rows.Single(r => r.PhysicalName != LegacyIndexName).PhysicalName].ShouldContain("$.Seq", Case.Sensitive); + } + + [TestMethod] + public async Task CompositeDeclaration_IsDeferredOnlyWhenTheOldIndexLeadsWithItsFirstProperty() + { + const string composite = "CREATE INDEX idx_pair_Item ON JsonValue(FullTypeName, CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC), JSON_EXTRACT(Data, '$.Group'));"; + + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + Execute(dbFile, composite); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(new Expression>[] { x => x.Seq, x => x.Group }, "pair"); + } + + ReadMetadata(dbFile).ShouldBeEmpty(); + ReadIndexDdl(dbFile).ShouldContainKey("idx_pair_Item"); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(new Expression>[] { x => x.Group, x => x.Seq }, "pair"); + } + + ReadMetadata(dbFile).ShouldHaveSingleItem().Definition.ShouldContain("$.Group", Case.Sensitive); + ReadIndexDdl(dbFile).ShouldNotContainKey("idx_pair_Item"); + } + + [TestMethod] + public async Task Declaration_OverAWholeDocumentIndex_IsLeftToOptimize() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + // What 4.x built for a value-type property: the boxed path indexed the document. + Execute(dbFile, $"DROP INDEX {LegacyIndexName}; CREATE INDEX {LegacyIndexName} ON JsonValue(FullTypeName, JSON_EXTRACT(Data, '$'));"); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + ReadMetadata(dbFile).ShouldBeEmpty(); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize().ShouldBeTrue(); + await AssertLookup(db); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + ReadIndexDdl(dbFile).ShouldNotContainKey(LegacyIndexName); + ExplainLookup(dbFile).ShouldContain(row.PhysicalName, Case.Sensitive); + } + + [TestMethod] + public async Task Declaration_WithNoProperties_DoesNotStopOptimize() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + Execute(dbFile, "CREATE INDEX idx_empty_Item ON JsonValue(FullTypeName);"); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(Array.Empty>>(), "empty"); + db.Optimize().ShouldBeTrue(); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [TestMethod] + public async Task Redeclared_BeforeOptimize_TheLatestDeclarationIsTheOneBuilt() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.ListIndexes().ShouldBeEmpty(); + + await db.CreateIndexAsync(x => x.Group, IndexName); + db.Optimize().ShouldBeTrue(); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + ReadIndexDdl(dbFile)[row.PhysicalName].ShouldContain("$.Group", Case.Sensitive); + } + + [TestMethod] + public async Task DropIndex_OfADeferredDeclaration_LeavesNothingForOptimize() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.DropIndex(IndexName).ShouldBeTrue(); + db.Optimize().ShouldBeTrue(); + await AssertLookup(db); + } + + ReadMetadata(dbFile).ShouldBeEmpty(); + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl.Keys.ShouldNotContain(k => k.StartsWith(LegacyIndexName + "_", StringComparison.Ordinal)); + } + + [DataTestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task OperationsDuringOptimize_AllSucceed_AndNothingIsLost(bool persistConnection) + { + const int rows = 20_000; + + var dbFile = await SeedLegacyStore(rows); + var (path, dbName) = Split(dbFile); + int writes = 0; + int reads = 0; + + using (var db = await ReopenDb(path, dbName, autoOptimize: false, persistConnection: persistConnection).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + + var optimize = Task.Run(db.Optimize); + + var readers = Enumerable.Range(0, 3).Select(_ => Task.Run(async () => + { + do + { + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBeGreaterThanOrEqualTo(rows); + Interlocked.Increment(ref reads); + } + while (!optimize.IsCompleted); + })); + + var writer = Task.Run(async () => + { + do + { + await db.WriteObjectAsync(new Item { Key = $"written-{writes}", Group = "G0", Seq = rows + writes }, x => x.Key); + writes++; + } + while (!optimize.IsCompleted); + }); + + (await optimize).ShouldBeTrue(); + await Task.WhenAll(readers.Append(writer)); + + reads.ShouldBeGreaterThan(0); + (await db.CountObjectsAsync()).ShouldBe(rows + writes); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadScalar(dbFile, "SELECT COUNT(*) FROM JsonValue").ShouldBe(rows + writes); + ReadText(dbFile, "PRAGMA integrity_check").ShouldBe("ok"); + } + + [TestMethod] + public async Task Optimize_LetsWaitingOperationsRunBetweenItsSteps() + { + const int declarations = 12; + + var dbFile = await SeedLegacyStore(20_000); + var (path, dbName) = Split(dbFile); + + Execute( + dbFile, + string.Concat(Enumerable.Range(0, declarations).Select(i => + $"CREATE INDEX idx_i{i}_Item ON JsonValue(FullTypeName, CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC));"))); + + using var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync(); + + for (int i = 0; i < declarations; i++) + { + await db.CreateIndexAsync(x => x.Seq, $"i{i}"); + } + + Task optimize = null; + int asynchronous = 0; + int synchronous = 0; + using var started = new ManualResetEventSlim(); + + var asyncCaller = Task.Run(async () => + { + started.Wait(); + + while (!optimize!.IsCompleted) + { + await db.CountObjectsAsync(); + + if (!optimize.IsCompleted) + { + asynchronous++; + } + } + }); + + var syncCaller = Task.Run(() => + { + started.Wait(); + + while (!optimize!.IsCompleted) + { + db.ListIndexes(); + + if (!optimize.IsCompleted) + { + synchronous++; + } + } + }); + + optimize = Task.Run(db.Optimize); + started.Set(); + + (await optimize).ShouldBeTrue(); + await Task.WhenAll(asyncCaller, syncCaller); + + asynchronous.ShouldBeGreaterThanOrEqualTo(2); + synchronous.ShouldBeGreaterThanOrEqualTo(2); + } + + [TestMethod] + public async Task Optimize_WithABlobStreamOpen_LeavesTheWorkForALaterCallWithoutHoldingTheGate() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + + using (var blob = new MemoryStream(new byte[4096])) + { + await db.WriteBlobAsync(blob, "blob-1"); + } + + var stream = await db.ReadBlobAsync("blob-1"); + var timer = System.Diagnostics.Stopwatch.StartNew(); + + db.Optimize().ShouldBeFalse(); + timer.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(20)); + + await AssertLookup(db); + await stream.DisposeAsync(); + + db.Optimize().ShouldBeTrue(); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile).ShouldNotContainKey(LegacyIndexName); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [TestMethod] + public async Task Optimize_WithABlobStreamOpenAtTheCompaction_LeavesItForALaterCall() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + using (var blob = new MemoryStream(new byte[4096])) + { + await db.WriteBlobAsync(blob, "blob-1"); + } + + var stream = await db.ReadBlobAsync("blob-1"); + + db.Optimize().ShouldBeFalse(); + stream.ReadByte().ShouldBe(0); + + await stream.DisposeAsync(); + + db.Optimize().ShouldBeTrue(); + await AssertLookup(db); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [TestMethod] + public async Task ConcurrentOptimizeCalls_BothFinish() + { + var dbFile = await SeedLegacyStore(5_000); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + + var results = await Task.WhenAll(Task.Run(db.Optimize), Task.Run(db.Optimize)); + + results.ShouldAllBe(finished => finished); + await AssertLookup(db); + } + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadMetadata(dbFile).ShouldHaveSingleItem(); + } + + [TestMethod] + public async Task OptimizeAsync_DoesTheSameWork_AndStopsWhenCancelled() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + + await Should.ThrowAsync(async () => await db.OptimizeAsync(cancelled.Token)); + await AssertLookup(db); + db.ListIndexes().ShouldBeEmpty(); + + (await db.OptimizeAsync()).ShouldBeTrue(); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile).ShouldNotContainKey(LegacyIndexName); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + } + + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task DisconnectOrDispose_DuringOptimize_LeavesAStoreThatOpens(bool dispose) + { + foreach (int delay in new[] { 0, 1, 2, 5, 10, 20, 40 }) + { + var dbFile = await SeedLegacyStore(5_000); + var (path, dbName) = Split(dbFile); + + var db = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync(); + await db.CreateIndexAsync(x => x.Seq, IndexName); + + var optimize = Task.Run(db.Optimize); + await Task.Delay(delay); + + if (dispose) + { + db.Dispose(); + } + else + { + await db.DisconnectAsync(); + } + + try + { + await optimize; + } + catch (Exception ex) when (ex is ArgumentNullException or ObjectDisposedException) + { + // Already disconnected when it started: the check every operation makes. + } + + db.Dispose(); + + using var reopened = await ReopenDb(path, dbName, autoOptimize: false).ConnectAsync(); + await reopened.CreateIndexAsync(x => x.Seq, IndexName); + reopened.Optimize().ShouldBeTrue(); + await AssertLookup(reopened); + (await reopened.CountObjectsAsync()).ShouldBe(5_000); + } + } + + [TestMethod] + public async Task StoreWithIncrementalAutoVacuum_ReclaimsInPlace_OnlyWhenATenthIsFree() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(5_000), x => x.Key); + await db.WriteObjectsAsync(Items(500).Select(x => new Item { Key = "other-" + x.Key, Group = x.Group, Seq = x.Seq }), x => x.Key, partition: "kept"); + + db.Optimize().ShouldBeTrue(); + } + + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.DeleteObjectsAsync(filter: FilterBuilder.Create().Filter(FilterType.LessThan, x => x.Seq, 10L)); + } + + long freeAfterAFewDeletes = ReadPragma(dbFile, "freelist_count"); + var hash = FileHash(dbFile); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + db.Optimize().ShouldBeTrue(); + } + + // Under a tenth free: left alone. + ReadPragma(dbFile, "freelist_count").ShouldBe(freeAfterAFewDeletes); + FileHash(dbFile).ShouldBe(hash); + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + await db.DeleteObjectsAsync(); + } + + ReadPragma(dbFile, "freelist_count").ShouldBeGreaterThan(0); + long size = new FileInfo(dbFile).Length; + + using (var db = await ReopenDb(path, dbName).ConnectAsync()) + { + db.Optimize().ShouldBeTrue(); + (await db.CountObjectsAsync(partition: "kept")).ShouldBe(500); + } + + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + new FileInfo(dbFile).Length.ShouldBeLessThan(size); + } + + [TestMethod] + public void ConstructorOfEarlierReleases_IsKept() + { + var (path, dbName) = NewDbPath(); + + var constructor = typeof(Tycho).GetConstructor( + new[] + { + typeof(string), typeof(IJsonSerializer), typeof(string), typeof(string), + typeof(bool), typeof(bool), typeof(bool), typeof(bool), typeof(int), + typeof(TychoPerformanceProfile), typeof(int?), typeof(long?), + }); + + constructor.ShouldNotBeNull(); + +#if ENCRYPTED + const string password = DbPassword; +#else + const string password = null; +#endif + + using var db = (Tycho)constructor.Invoke( + new object[] { path, Serializer, dbName, password, true, false, false, true, 30, TychoPerformanceProfile.Mobile, null, null }); + + db.Connect(); + } +} diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs index 4770608..3c93165 100644 --- a/TychoDB.UnitTests/PlannerStatisticsTests.cs +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -117,19 +117,22 @@ public async Task Reconnect_AfterBulkLoadAndDispose_PartialIndexChosen() [TestMethod] public async Task Connect_RemovesStatisticsLeftByAnEarlierRelease() { - var dbFile = await SeedIndexedStore(); - var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + 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); + 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); - } + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } - ReadStatRows(dbFile).ShouldBeEmpty(); - AssertGroupLookupUsesPartialIndex(dbFile); + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); + } } [TestMethod] @@ -197,10 +200,13 @@ public async Task Connect_OnAReadOnlyFile_LeavesTheStatisticsAndSucceeds() Assert.Inconclusive("The file stays writable for this user, so the read-only connect cannot be exercised."); } - using var db = await StoreFixture.ReopenDb(path, dbName).ConnectAsync(); - await db.CreateIndexAsync(x => x.Seq, StoreFixture.IndexName); - await StoreFixture.AssertLookup(db); - (await db.CountObjectsAsync()).ShouldBe(100); + foreach (var autoOptimize in new[] { true, false }) + { + using var db = await StoreFixture.ReopenDb(path, dbName, autoOptimize: autoOptimize).ConnectAsync(); + await db.CreateIndexAsync(x => x.Seq, StoreFixture.IndexName); + await StoreFixture.AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(100); + } } finally { @@ -487,13 +493,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/StoreFixture.cs b/TychoDB.UnitTests/StoreFixture.cs index c775ec5..152cfe2 100644 --- a/TychoDB.UnitTests/StoreFixture.cs +++ b/TychoDB.UnitTests/StoreFixture.cs @@ -260,13 +260,13 @@ public static Tycho BuildDb(string path, string dbName) } /// Reopens an existing database without rebuilding it. - public static Tycho ReopenDb(string path, string dbName, bool persistConnection = true, bool useConnectionPooling = true) + public static Tycho ReopenDb(string path, string dbName, bool persistConnection = true, bool useConnectionPooling = true, bool autoOptimize = true) { SqliteConnection.ClearAllPools(); #if ENCRYPTED - return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: useConnectionPooling); + return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: useConnectionPooling, autoOptimize: autoOptimize); #else - return new Tycho(path, Serializer, dbName, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: useConnectionPooling); + return new Tycho(path, Serializer, dbName, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, useConnectionPooling: useConnectionPooling, autoOptimize: autoOptimize); #endif } diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 2adc21b..bd90ea8 100644 --- a/TychoDB/Queries.cs +++ b/TychoDB/Queries.cs @@ -51,15 +51,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, @@ -79,6 +70,20 @@ 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. Freeing their pages on an upgraded store takes time + // proportional to their size, so the connect script drops them only when autoOptimize + // is on (see Tycho.Optimize). + public static readonly string[] LegacyIndexNames = + { + "idx_jsonvalue_fulltypename", + "idx_jsonvalue_key_fulltypename", + "idx_jsonvalue_key_fulltypename_partition", + "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 @@ -96,14 +101,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. The - /// pragma that only applies to a database being created is included for a new file - /// only. + /// given performance profile, honoring optional cache-size / mmap overrides, and + /// 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 newDatabase = true) { bool desktop = profile == TychoPerformanceProfile.Desktop; @@ -113,7 +119,7 @@ public static string BuildConnectionScript( int walAutocheckpoint = desktop ? DesktopWalAutocheckpoint : MobileWalAutocheckpoint; long journalSizeLimit = desktop ? DesktopJournalSizeLimitBytes : MobileJournalSizeLimitBytes; - var sb = new System.Text.StringBuilder(CreationPragma.Length + SharedPragmas.Length + SchemaDdl.Length + 160); + var sb = new System.Text.StringBuilder(CreationPragma.Length + SharedPragmas.Length + SchemaDdl.Length + 320); var ic = System.Globalization.CultureInfo.InvariantCulture; if (newDatabase) @@ -128,6 +134,16 @@ public static string BuildConnectionScript( .Append("PRAGMA journal_size_limit = ").Append(journalSizeLimit.ToString(ic)).Append(";\n\n") .Append(SchemaDdl); + if (dropLegacyIndexes) + { + sb.Append('\n'); + + foreach (string indexName in LegacyIndexNames) + { + sb.Append(DropIndex(indexName)).Append('\n'); + } + } + return sb.ToString(); } @@ -468,7 +484,9 @@ public static string CreateIndexForJsonValue(string fullIndexName, string proper private const string MultiIndexJsonExtractSuffix = "')"; private const string MultiIndexCastPrefix = ", CAST(JSON_EXTRACT(Data, '"; private const string MultiIndexCastSuffix = "') as NUMERIC)"; - private const string MultiIndexOnJsonValue = "\nON JsonValue(FullTypeName"; + private const string WholeDocumentExpression = ", JSON_EXTRACT(Data, '$')"; + private const string IndexOnFullTypeName = "ON JsonValue(FullTypeName"; + private const string MultiIndexOnJsonValue = "\n" + IndexOnFullTypeName; private const string MultiIndexClose = ");"; // Partial-index shape. Leads with Partition (every read constrains @@ -620,6 +638,28 @@ FROM TychoIndex public static string StoredIndexSql(string createIndexStatement) => string.Concat("CREATE INDEX ".AsSpan(), createIndexStatement.AsSpan(CreateIndexPrefix.Length).TrimEnd(';')); + /// + /// Whether the non-partial index stored as can stand in for a + /// declaration led by until it is rebuilt. It leads with + /// FullTypeName and, in the string overload's shape, Partition, both equality-constrained + /// by every query, so it serves a filter on that property when the next column is the + /// expression the filter emits, in the form SQLite compares. An index over the whole + /// document, which is what 4.x built for a value-type property, serves nothing, but no + /// more than it ever did, so nothing is lost by leaving it in place. + /// + public static bool IndexStandsInFor(string indexSql, (string PropertyPathString, bool IsNumeric) firstPath) + { + string expression = firstPath.IsNumeric + ? string.Concat(MultiIndexCastPrefix, firstPath.PropertyPathString, MultiIndexCastSuffix) + : string.Concat(MultiIndexJsonExtractPrefix, firstPath.PropertyPathString, MultiIndexJsonExtractSuffix); + + return IndexLeadsWith(indexSql, expression) || IndexLeadsWith(indexSql, WholeDocumentExpression); + } + + private static bool IndexLeadsWith(string indexSql, string expression) + => indexSql.Contains(string.Concat(IndexOnFullTypeName, expression), StringComparison.Ordinal) + || indexSql.Contains(string.Concat(IndexOnFullTypeName, PartitionColumnSegment, expression), StringComparison.Ordinal); + // Planner statistics. TychoDB gathers none: SQLite's default heuristics choose the // right index for every query it emits. These find and delete rows left in the file, // reloading so the open connection forgets them. The table stays, because ANALYZE diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 50312a8..2affd1f 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -48,6 +48,11 @@ private const string // timeout would hold the gate for 30 s, with every other operation waiting behind it. private const int MaintenanceBusyTimeout = 1; + // Between two maintenance steps the gate stays free this long, because a SemaphoreSlim + // is not fair: a thread that releases and at once waits again can beat the synchronous + // waiter it just woke, and that waiter would sit out the whole of Optimize. + private const int StepPauseMilliseconds = 1; + // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); @@ -61,6 +66,12 @@ private const string private readonly IJsonSerializer _jsonSerializer; private readonly bool _persistConnection; private readonly bool _requireTypeRegistration; + private readonly bool _autoOptimize; + + // Declarations CreateIndex left for Optimize under autoOptimize: false, keyed as + // TychoIndex is. Read and written under the gate. Kept in memory because apps declare + // their indexes on every launch: a declaration is never read back out of the file. + private readonly Dictionary<(string IndexName, string TypeName), IndexDefinition> _deferredIndexes = new(); // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -122,6 +133,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 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 those indexes in place, and CreateIndex leaves a declaration + /// the previous release's index can still serve to — and call + /// or at a convenient time, after + /// declaring the indexes. Default is true. + /// public Tycho( string dbPath, IJsonSerializer jsonSerializer, @@ -134,7 +155,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(); @@ -171,9 +193,42 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; + _autoOptimize = autoOptimize; _databasePath = databasePath; - _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, newDatabase: false); - _creationScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, newDatabase: true); + _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: false); + _creationScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: true); + } + + /// + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Tycho( + string dbPath, + IJsonSerializer jsonSerializer, + string dbName, + string? password, + bool persistConnection, + bool rebuildCache, + bool requireTypeRegistration, + bool useConnectionPooling, + int commandTimeout, + TychoPerformanceProfile performanceProfile, + int? cacheSizeKb, + long? mmapSizeBytes) + : this( + dbPath, + jsonSerializer, + dbName, + password, + persistConnection, + rebuildCache, + requireTypeRegistration, + useConnectionPooling, + commandTimeout, + performanceProfile, + cacheSizeKb, + mmapSizeBytes, + autoOptimize: true) + { } /// @@ -2155,7 +2210,8 @@ private readonly record struct IndexDefinition( string MetadataTypeName, string PhysicalName, string LegacyPhysicalName, - string CommandText); + string CommandText, + (string PropertyPathString, bool IsNumeric)[] PropertyPaths); /// /// Builds the physical index name and the CREATE INDEX statement for a set of @@ -2185,7 +2241,8 @@ private static IndexDefinition BuildIndexDefinition( fullTypeName ?? objectTypeName, physicalName, legacyName, - Queries.CreateIndexForJsonValue(physicalName, propertyPaths, fullTypeName)); + Queries.CreateIndexForJsonValue(physicalName, propertyPaths, fullTypeName), + propertyPaths); } /// @@ -2269,13 +2326,20 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) /// word — counts as stale, and a stale index is rebuilt. /// /// + /// With every change happens here. Without it, nothing + /// is written while the index an earlier release built for this declaration can stand + /// in for it, and the work is left to ; a declaration with no such + /// index is built here either way, because no index is the slower outcome. + /// + /// /// An 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 not this - /// declaration's to drop. + /// declaration's, so it neither serves it nor is dropped for it. /// /// - private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) + /// True when work was left to . + private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition, bool migrateInline) { using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); @@ -2295,11 +2359,22 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de UpsertIndexMetadata(conn, definition); } - if (legacyOrphan) + if (legacyOrphan && migrateInline) { ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); } + transaction.Commit(); + return legacyOrphan && !migrateInline; + } + + string? previousSql = hasLegacyName ? (legacyOrphan ? legacySql : null) : physicalSql; + + if (!migrateInline + && previousSql is not null + && definition.PropertyPaths.Length > 0 + && Queries.IndexStandsInFor(previousSql, definition.PropertyPaths[0])) + { transaction.Commit(); return true; } @@ -2323,7 +2398,7 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de UpsertIndexMetadata(conn, definition); transaction.Commit(); - return true; + return false; } catch (Exception ex) { @@ -2332,6 +2407,26 @@ private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition de } } + /// + /// Applies a declaration and notes whether it left work for . + /// Runs under the gate. + /// + private bool DeclareIndex(SqliteConnection conn, IndexDefinition definition) + { + var key = (definition.IndexName, definition.MetadataTypeName); + + if (ExecuteCreateIndex(conn, definition, migrateInline: _autoOptimize)) + { + _deferredIndexes[key] = definition; + } + else + { + _deferredIndexes.Remove(key); + } + + return true; + } + /// One row of the TychoIndex metadata table, as stored. private readonly record struct IndexMetadataRow(string PhysicalName, string Definition, long ShapeVersion); @@ -2422,8 +2517,8 @@ private Tycho CreateIndexCore( _connection .WithConnectionBlock( _connectionGate, - definition, - static (conn, state) => ExecuteCreateIndex(conn, state), + (tycho: this, definition), + static (conn, state) => state.tycho.DeclareIndex(conn, state.definition), _persistConnection); return this; @@ -2448,8 +2543,8 @@ private ValueTask CreateIndexCoreAsync( return _connection .WithConnectionBlockAsync( _connectionGate, - definition, - static (conn, state) => ExecuteCreateIndex(conn, state), + (tycho: this, definition), + static (conn, state) => state.tycho.DeclareIndex(conn, state.definition), _persistConnection, cancellationToken); } @@ -2584,8 +2679,8 @@ public bool DropIndex(string indexName) return _connection .WithConnectionBlock( _connectionGate, - (indexName, typeName: TypeCache.FullName), - static (conn, state) => ExecuteDropIndex(conn, state.indexName, state.typeName), + (tycho: this, indexName, typeName: TypeCache.FullName), + static (conn, state) => state.tycho.ExecuteDropIndex(conn, state.indexName, state.typeName), _persistConnection); } @@ -2604,13 +2699,13 @@ public ValueTask DropIndexAsync(string indexName, CancellationToken return _connection .WithConnectionBlockAsync( _connectionGate, - (indexName, typeName: TypeCache.FullName), - static (conn, state) => ExecuteDropIndex(conn, state.indexName, state.typeName), + (tycho: this, indexName, typeName: TypeCache.FullName), + static (conn, state) => state.tycho.ExecuteDropIndex(conn, state.indexName, state.typeName), _persistConnection, cancellationToken); } - private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, string typeName) + private bool ExecuteDropIndex(SqliteConnection conn, string indexName, string typeName) { using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); @@ -2618,6 +2713,11 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st { string? physicalName = ReadRecordedIndex(conn, indexName, typeName)?.PhysicalName; + if (_deferredIndexes.Remove((indexName, typeName), out var deferred)) + { + physicalName ??= deferred.PhysicalName; + } + if (physicalName is null) { transaction.Commit(); @@ -2652,7 +2752,8 @@ 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. + /// Indexes created directly against the database outside Tycho are not listed, nor is + /// a declaration left to until it has been built. /// /// The recorded indexes, ordered by type then index name. public IReadOnlyList ListIndexes() @@ -2686,9 +2787,169 @@ public IReadOnlyList ListIndexes() } /// - /// Runs maintenance under the gate, on the connection as it is now. A disconnected - /// instance ends the work, and a full volume or a file in use leaves it for a later call; - /// neither is a failure. + /// Does the one-time work an upgraded store needs: deletes planner statistics an + /// external ANALYZE left; drops the four redundant indexes 4.x created; builds + /// every index CreateIndex left for it under autoOptimize: false and drops + /// the index the previous release built in its place, along with the per-type index a + /// 4.x rollback recreated next to a current one; and returns the pages all of that freed + /// to the file 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 to do it reads the schema and writes nothing, so calling it on every + /// launch is fine. Declare the indexes first: only declarations this instance has seen + /// are built, and the indexes the others replace would be copied by the compaction. + /// + /// Each drop and build is one step, and every other operation on this instance runs + /// between steps: an operation waits for the step in progress, never for the whole + /// call. The compaction is one step, and usually the longest: on a 1.76M-row, 2.37 GB + /// store upgraded from 4.x it took 3 to 13 s on a desktop, depending on its load, and + /// the call as a whole about 20 s. A phone takes longer. An interruption between or + /// during steps leaves a working store, and the next call goes on from there. The work + /// runs on the calling thread, which must not be a UI thread. The compaction replaces the + /// file, so keep to one instance per file (see ). + /// + /// + /// + /// True when nothing is left to do. False when work remains for a later call: the + /// volume lacks the free space for the compacted copy or for a rebuild, the file or a + /// blob stream of this instance is in use, or the instance was disconnected or disposed. + /// + public bool Optimize() + { + EnsureConnected(); + + return RunMaintenance(alwaysReclaim: false); + } + + /// + /// Asynchronously does what does, with the same cost. Only the + /// first step, which reads the schema, runs on the calling thread. The token is observed + /// between steps: a step in progress runs to its end. + /// + /// A token to cancel the asynchronous operation. + /// A ValueTask containing the value returns. + public async ValueTask OptimizeAsync(CancellationToken cancellationToken = default) + { + EnsureConnected(); + + bool firstStep = true; + + foreach (var step in MaintenanceSteps(alwaysReclaim: false)) + { + if (!firstStep) + { + await Task.Delay(StepPauseMilliseconds, cancellationToken).ConfigureAwait(false); + } + + firstStep = false; + + await _connectionGate.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + if (!RunMaintenanceStep(step)) + { + return false; + } + } + finally + { + _connectionGate.Release(); + } + } + + return true; + } + + private bool RunMaintenance(bool alwaysReclaim) + { + bool firstStep = true; + + foreach (var step in MaintenanceSteps(alwaysReclaim)) + { + if (!firstStep) + { + Thread.Sleep(StepPauseMilliseconds); + } + + firstStep = false; + + _connectionGate.Wait(); + + try + { + if (!RunMaintenanceStep(step)) + { + return false; + } + } + finally + { + _connectionGate.Release(); + } + } + + return true; + } + + /// + /// The work of as steps that each take the gate on their own. + /// Everything a step needs is read under the gate when the step runs, since any other + /// operation can run between two steps. A step that leaves its work for a later call ends + /// the run: the compaction, last, would copy whatever the earlier steps did not remove. + /// + private IEnumerable> MaintenanceSteps(bool alwaysReclaim) + { + var legacyIndexes = new List(); + var deferredIndexes = new List<(string IndexName, string TypeName)>(); + + yield return conn => + { + RemoveLeftoverStatistics(conn); + + foreach (string indexName in Queries.LegacyIndexNames) + { + if (ReadIndexSql(conn, indexName) is not null) + { + legacyIndexes.Add(indexName); + } + } + + deferredIndexes.AddRange(_deferredIndexes.Keys); + return true; + }; + + foreach (string indexName in legacyIndexes) + { + yield return conn => + { + ExecuteNonQuery(conn, Queries.DropIndex(indexName)); + return true; + }; + } + + foreach (var key in deferredIndexes) + { + yield return conn => + { + if (_deferredIndexes.TryGetValue(key, out var definition)) + { + ExecuteCreateIndex(conn, definition, migrateInline: true); + _deferredIndexes.Remove(key); + } + + return true; + }; + } + + yield return conn => ReclaimFreePages(conn, alwaysReclaim); + } + + /// + /// Runs one step of under the gate, on the connection as it is + /// now. A disconnected instance ends the work, and a full volume or a file in use leaves + /// it for a later call; neither is a failure. /// private bool RunMaintenanceStep(Func step) { @@ -2740,16 +3001,23 @@ private static bool CanWaitForALaterCall(Exception ex) /// 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 — is converted by - /// . Later calls reclaim in place. + /// . Later calls reclaim in place, when at least a tenth of the + /// file is free so that a store with a little churn is left alone, or whenever + /// asks for it. /// - private bool ReclaimFreePages(SqliteConnection conn) + private bool ReclaimFreePages(SqliteConnection conn, bool always) { if (ReadPragma(conn, Queries.AutoVacuumMode) != 2) { return CompactStore(conn); } - ExecuteNonQuery(conn, Queries.IncrementalVacuum); + long freePages = ReadPragma(conn, Queries.FreelistCount); + + if (always || (freePages > 0 && freePages * 10 >= ReadPragma(conn, Queries.PageCount))) + { + ExecuteNonQuery(conn, Queries.IncrementalVacuum); + } return true; } @@ -2976,7 +3244,9 @@ private static long ReadPragma(SqliteConnection conn, string pragma) /// 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 ). + /// is skipped when the space is not there (see ). Either way + /// the work does runs first, in the same steps, so that the + /// indexes it replaces are not copied. /// public void Cleanup(bool shrinkMemory = true, bool vacuum = false) { @@ -3003,16 +3273,7 @@ public void Cleanup(bool shrinkMemory = true, bool vacuum = false) if (vacuum) { - _connectionGate.Wait(); - - try - { - RunMaintenanceStep(ReclaimFreePages); - } - finally - { - _connectionGate.Release(); - } + RunMaintenance(alwaysReclaim: true); } } @@ -3298,8 +3559,8 @@ private SqliteConnection OpenConnection() /// /// Opens and runs on it. The /// statistics delete is best-effort: a store on a read-only file or a full volume - /// connects, and the planner stays misled until a connect that can write. Runs under the - /// gate. + /// connects, and the planner stays misled until a connect that can write; + /// reports the failure. Runs under the gate. /// private static void InitializeConnection(SqliteConnection connection, string script) { From 3526af4f37166fc1304b08115a109edb60606649 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:27 -0600 Subject: [PATCH 07/11] docs: describe the 5.4.0 upgrade path and set the package version --- CHANGELOG.md | 122 ++++++++++++ Directory.build.props | 2 +- README.md | 83 +++++++- docs/indexing-analysis.md | 5 + docs/planner-statistics-history.md | 243 +++++++++++++++++++++++ docs/planner-statistics-sampling.md | 287 +++++++++++++++++++++++++++ docs/planner-statistics-sampling.sql | 136 +++++++++++++ 7 files changed, 870 insertions(+), 8 deletions(-) create mode 100644 docs/planner-statistics-history.md create mode 100644 docs/planner-statistics-sampling.md create mode 100644 docs/planner-statistics-sampling.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 117fd5d..ce04b9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,127 @@ # Changelog +## 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, 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. At connect the delete is + best-effort: 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 + 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`), and `DropIndex` drops it together with the index. A legacy name + that another declaration records as its own index is left alone by both: 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 + 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. +- **`Cleanup(vacuum: true)` needed room for two copies of a store without incremental + auto-vacuum, and failed badly without it.** A full `VACUUM` writes the data twice, to a + temp copy and back through the WAL: on a 49 MB store with 75 MB free it failed with + `database or disk is full`, left `temp_store = FILE` on the connection, and failed again + on every call. It now compacts as `Optimize()` does (see below), and the deferred work + runs first so that the indexes it replaces are not copied. +- **`Connect`, `Disconnect`, `Dispose` and `Backup` ran outside the connection gate.** + `Disconnect` or `Dispose` during an operation closed the connection under it, and two + racing `Connect` calls opened two connections, the second waiting on the first's lock. + All four now take the gate, so they wait for the operation in progress. `Dispose` no longer + disposes the gate, on which a waiting operation would never wake; a call after it still + throws `ObjectDisposedException`. +- **A connection whose setup failed kept the file locked** until the finalizer ran, so the + retry got `database is locked`. It is disposed before the failure propagates. + +### Added + +- **`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 — 9 s on a 1.76M-row, + 2.37 GB store, since freeing an index's pages takes time proportional to its size — and + the first `CreateIndex` for each declaration drops the whole-table index 4.x built for it + and builds the partial one (15 s for six). Pass `autoOptimize: false` to defer both: + connect leaves the indexes in place, and `CreateIndex` leaves a declaration to `Optimize()` + while the index an earlier release built for it can still serve a filter on its first + property. Nothing is written, and connect and six declarations took 90 ms on that store. + An index over the whole document, which is what 4.x built for a value-type property, is + left in place the same way: it never served a query, so nothing is lost. A declaration + whose old index covers another property is built at once either way. Apps declare their + indexes on every launch, so a deferred declaration is kept in memory: call `Optimize()` + after declaring them. Without it a 4.x store keeps its old indexes and its size and + otherwise behaves as it did. + + `Optimize()` / `OptimizeAsync()` do the work in steps: delete leftover statistics, drop + each of the four indexes, build each deferred index and drop what it replaces (in one + transaction, so an interruption leaves one or the other), and return the freed pages to + the file system. Every other operation runs between steps, so a call waits for the step + in progress, never for the whole of it: about 20 s in all on that store, with reads and + writes running throughout, none failing, and none waiting more than about 4 s. `Optimize()` + runs on the calling thread, so call it from a background thread; `OptimizeAsync()` runs + only its first step there, and its token is observed between steps. Both return true when + nothing is left to do and false when work remains for a later call: the volume lacks the + space, the file or a blob stream of this instance is in use, or the instance was + disconnected. Idempotent: with nothing to do they read the schema and write nothing, so + calling them on every launch is fine. + + A store with incremental auto-vacuum reclaims in place when at least a tenth of the file + is free. One without it — every 4.x store, whose connect script set the pragma too late — + is compacted: the live pages are written into a copy next to the database with `VACUUM + INTO`, the copy is flushed to disk and takes the file's permissions, the connection closes, + the `-wal` and `-shm` are deleted, the copy is renamed over the file, and the same + connection object reopens on it, so operations waiting on the gate run on the new file. + That converts the store and returned 1.3 GB on that one (2.37 GB to 1.04 GB). It needs + free space for the compacted copy only, and leaves the database untouched until the rename, + which is atomic: an interruption costs at most a leftover copy, which the next connect + removes. It is skipped, to be retried by the next call, when the volume lacks the space, + SQLite reports it full, another connection holds a lock on the file, or the WAL survives + the close, because the close could not checkpoint it. The swap replaces the file, so + attributes an app set on it other than its permissions, such as an iOS backup exclusion or + a file protection class, do not carry over. It needs one `Tycho` instance per file, with + `persistConnection: false` too: a connection that has the file open without holding a + lock, such as one still connecting, cannot be detected, and after the swap it can lose + what it writes. + + With the whole-table 4.x indexes gone, 50,000-row bulk writes on a 1.8M-row, 3 GB 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. The constructor of earlier releases is kept as an overload, so code compiled against + 5.3 keeps running. + ## 5.3.1 — 2026-10-05 ### Fixed 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 4e3aa37..4e88d00 100644 --- a/README.md +++ b/README.md @@ -492,12 +492,61 @@ 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. -- **Statistics are refreshed** with a bounded `ANALYZE` after an index is created, so a - new index is usable by the very next query. + `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 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. +- **Keep to one `CreateIndex` overload per store.** The string overload's index leads with + `FullTypeName, Partition`, so it also suits a read of a whole type, and SQLite settles a + tie for the index declared last. In a store with both kinds, an `Or`, `In` or null filter + on a generic index can go through the string overload's index and read every row of the + type. Equality and range filters are not affected. +- **Upgrading a large store from 4.x takes tens of seconds, once.** By default that work + runs on the calling thread: connecting drops the four redundant indexes 4.x created + (9 s on a 1.76M-row, 2.37 GB store), and the first `CreateIndex` for each declaration + drops the whole-table index 4.x built for it and builds the partial one (15 s for six). + An app that connects on its UI thread should pass `autoOptimize: false`. Connect and + the declarations then took 90 ms on that store and write nothing, queries keep using + the indexes 4.x built, and `Optimize()` does the work when the app chooses. A declaration + whose old index covers another property is built at once either way, because no index + is slower. Without `Optimize()` a 4.x store simply keeps its old indexes and its size. +- **`Optimize()` does that work in steps, from a background thread.** It deletes leftover + statistics, drops the four indexes, builds each deferred index, and compacts a store + that has no incremental auto-vacuum (every 4.x store): the live pages are written into + a copy next to the database with `VACUUM INTO`, the copy is flushed to disk, and it is + renamed over the file. It took about 20 s on that store, which went from 2.37 GB to + 1.04 GB. Other operations run between steps, so a call waits for the step in progress, + about 4 s at the longest on that store on a Mac and longer on a phone, rather than for + all of it. Interrupt it at any point and the store still works; the next call goes on + from there. Call it after declaring your indexes: it only builds what this instance has + been told about. It returns `false` when work remains for a later call, such as when + the disk lacks room for the copy, and it is free once there is nothing left to do, so + calling it on every launch is fine. +- **Compaction replaces the database file.** Its permissions carry over. Anything else + your app set on the file, such as an iOS backup exclusion or a file protection class, + does not, so set it again after the first `Optimize()`. Keep to one `Tycho` instance per + file, with `persistConnection: false` too: a connection that has the file open without + holding a lock, such as one still connecting, cannot be detected, and after the swap it + can lose what it writes. Nothing shrinks the file on the default path until you call + `Optimize()` or `Cleanup(vacuum: true)`. +- **The upgrade pays back on every write.** With the whole-table 4.x indexes gone, + 50,000-row bulk writes on a 1.8M-row, 3 GB 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). @@ -541,6 +590,16 @@ db.Disconnect(); // Or disconnect asynchronously await db.DisconnectAsync(); + +// 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) + .AddTypeRegistration(x => x.Id); +await deferredDb.ConnectAsync(); +deferredDb.CreateIndex(x => x.Age, "age_index"); +await Task.Run(() => deferredDb.Optimize()); ``` ### Device Performance Profiles @@ -591,8 +650,18 @@ await db.DeleteObjectsAsync(); ### Database Maintenance ```csharp -// Optimize database performance and reduce size +// Optimize database performance and reduce size. With vacuum: true this does what +// Optimize does, and takes as long 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 +// compact the file (skipped when the disk lacks room for the compacted copy). A no-op once +// done, so it is fine on every launch. It runs on the calling thread and takes tens of +// seconds on a large store upgraded from 4.x, so call it from a background thread, never +// the UI thread. Other operations run between its steps. False means work remains for a +// later call; a failure throws a TychoException and leaves a working store. +bool finished = await Task.Run(() => db.Optimize()); ``` ## LINQ Support 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-history.md b/docs/planner-statistics-history.md new file mode 100644 index 0000000..96463bf --- /dev/null +++ b/docs/planner-statistics-history.md @@ -0,0 +1,243 @@ +# 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. + +--- + +## 15. Consolidation for release + +**What happened:** Three independent reviews, on real stores, found the compaction and the deferral not ready: + +- **Calls during a compaction failed.** The compaction replaced the connection object, and every call already waiting held the old one: 137 of 137 lookups failed during one `Optimize()`. +- **`Optimize()` blocked every other call** for its whole run, 23–34 s on the real stores. +- **A deferred index could be missing for days.** `autoOptimize: false` deferred whenever any index had the old name, even one on another property, and the lookup then read the whole type. +- **`Optimize()` could get stuck.** It read a pending definition back from the file and refused one it could not rebuild byte for byte, on every call, for good. A hand-written parser existed only to make that check. +- **`Disconnect` and `Dispose` were not serialized with other calls,** so one during `Optimize()` could leave the file locked by a connection nothing owned. +- **Smaller problems:** a leftover copy could stay forever, the SQLCipher build renamed an unsynced copy over the store, the new constructor parameter broke binary compatibility, and `Cleanup(vacuum: true)` before `Optimize()` copied all the 4.x indexes. + +**Changed:** + +- **Deferred declarations stay in memory.** Apps declare their indexes on every launch, so nothing needs storing. `CreateIndex` now writes nothing while it defers, and `Optimize()` builds through the same code as `CreateIndex`. The parser, the pending rows and their second copy of the rebuild logic are gone. +- **`Optimize()` works in steps** and lets other calls run between them. The longest wait fell to about 4 s on the 2.37 GB store. +- **The compaction keeps the connection object:** it closes it, swaps the file and reopens it. +- **Only an index that can stand in for the declaration defers it.** Its first column must be the first declared property, or the whole document, which 4.x indexed for value-type properties and which never served a query anyway. Anything else is built at once. +- **`Connect`, `Disconnect`, `Dispose` and `Backup` take the same lock as every other call.** +- **The compacted copy is flushed to disk** and keeps the file's permissions. Connecting removes a leftover copy. +- **`Cleanup(vacuum: true)` does the deferred work first.** +- **`Optimize()` returns whether anything is left to do.** A full disk leaves the work for a later call instead of failing. +- **The `secure_delete` toggle is gone.** It only helped the SQLCipher build, which nothing uses, and it left pages unzeroed when a compaction was skipped. +- **The old constructor is back** as an overload, so code compiled against 5.3 keeps running. + +**Result** on the 2.37 GB store, with reads and writes running throughout: + +| | | +|---|---| +| Connect plus six `CreateIndex` | 70–90 ms | +| `Optimize()` | 19–22 s, 0 failed calls | +| Longest wait for any one call | about 4 s (was the whole run) | +| File size | 2.37 GB → 1.04 GB | + +Tested on stores written by 14 releases from 3.2.2 to 5.3.1 in every connection mode, 224 of 224; with the process killed at random and at each step of the swap; on full disks; with each step of the swap made to fail; and on the iOS simulator and an Android emulator. + +--- + +## 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 write nothing, and `Optimize()` on a background thread does the drops, rebuilds and compaction in steps, with other calls running between them. +- **Two filters:** filtering on two properties needs a composite index. diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md new file mode 100644 index 0000000..2c14077 --- /dev/null +++ b/docs/planner-statistics-sampling.md @@ -0,0 +1,287 @@ +# 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, 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 + +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'; +``` + +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 + `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, chooses the general index, and reads and JSON-parses +every row of the type on each lookup. + +## Fix + +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 +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, and a query that filters on two properties is what a composite index is for. + +Two more cases rest on the planner's tie-break, which goes to the index declared last. +`Or`, `In` and null filters on an indexed property cost about the same through the +property's partial index as through any other index that leads with `FullTypeName, +Partition`, and reading through the latter reads the whole type: + +- A store that mixes the two `CreateIndex` overloads. Declared after a generic index, the + string overload's index takes those filters, for good. Equality and range filters are not + affected. MoveScoutPro's stores each use one overload, and the README says to. +- A store part-way through the upgrade, with a partial index built on a type whose other + indexes are still 4.x ones. Those filters then go through the general index until + `Optimize` finishes. + +## 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 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. +- `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` (nothing written, served by the 4.4.2 index) and + then optimized (rebuilt, drops done, store compacted and converted, nothing written on + the next launch); the same store under `autoOptimize: true`; a declaration the old index + cannot serve; the string overload's 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 — reads and writes succeed throughout and run between its steps, + `Disconnect` and `Dispose` during it leave a store that opens, a copy that cannot be + written throws and keeps the store serving, a leftover copy is removed at connect, the + file's permissions and a symbolic link survive, and it is skipped while another + connection holds a lock on the file. + +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. + +## Cost + +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 part 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. On a 1.76M-row, 2.37 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 — 15 s more. Each build scans the table, +and SQLite cannot build several indexes in one pass, so the builds are most of that time. +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 a production store once the six whole-table per-type +indexes go too (table below). + +`autoOptimize: false` connects without the drops, and `CreateIndex` writes nothing while the +index an earlier release built can still serve a filter on the declaration's first property +— 90 ms for the connect and six declarations on that store. The whole-document index 4.x +built for a value-type property is left in place too: it never served a query, so waiting +loses nothing, and building at once would stall the caller for seconds. The deferred +declaration is kept in memory, because apps declare their indexes on every launch, and +`Optimize` builds it through the same code `CreateIndex` uses. A declaration whose old index +covers another property is built at once. + +`Optimize`/`OptimizeAsync` then do the statistics delete, the drops, the rebuilds and a +compaction that returns the freed pages — 1.3 GB on that store — since a 4.x store has no +incremental auto-vacuum and nothing else can. Each is a step that takes the gate on its own, +so other operations run between steps and wait only for the step in progress, about 4 s at +the longest on that store. The compaction is one step: nothing can write during the copy. + +The compaction is `VACUUM INTO` a copy next to the database, then a swap: the copy is +flushed to disk and takes the file's permissions, the connection closes, the copy is renamed +over the file, and the same connection object 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 another connection holds a lock on the file or the WAL survives the close, which happens +only when the close could not checkpoint it. A connection with the file open and no lock, +such as one retrying a busy file, cannot be detected, and after the rename it would read the +old file with the `-wal` of the new one, so the swap needs one instance per file. A store +converted this way runs with incremental auto-vacuum, as a store created by 5.1 or later +does, which costs about 7% on bulk inserts and 12% on partition deletes against the same +store without it. + +## 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 left to `Optimize`, no DDL | 69 ms (67 of it the first call's JIT) | +| Lookups before `Optimize`, 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, 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 | + +| `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 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 leave it to `Optimize()`, 15 ms for `Optimize()` to rebuild it, 9 ms inline. + +The compaction that replaced the full `VACUUM`, and the steps, measured through the library +on a copy of another 4.4.2 pricing store (1,763,583 rows, 2.37 GB, the same eleven indexes, +e_sqlite3 3.50.3, NVMe, warm), with one task running the app's four lookups in a loop, one +writing, and one making a synchronous call, for the whole of `Optimize()`: + +| `autoOptimize: false` | | +|---|---| +| Connect, six `CreateIndex` | 38–52 ms, 32–39 ms | +| `Optimize()`: four drops, six rebuilds, `VACUUM INTO`, swap | 19–22 s | +| Calls during it | all succeeded, every write kept | +| Longest wait for one call | 3.4–4.3 s (the whole run before the steps) | +| File | 2.37 GB → 1.04 GB, `auto_vacuum` 2, freelist 0 | +| Largest WAL, peak memory | 11 MB, 187 MB | +| Next launch: `Optimize()` | 1.2 ms | + +| `autoOptimize: true` | | +|---|---| +| Connect, the four drops | 9.2 s | +| Six `CreateIndex` inline | 14.6 s | +| `Optimize()` on the next launch, the compaction alone | 3.1 s | + +A full `VACUUM` took the WAL to 1,043 MB on the same store. 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. + +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 + 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: no failures in Debug or Encrypted, 4 skipped. +- Stores written by 14 real releases, 3.2.2 to 5.3.1, each upgraded in 16 combinations of + `autoOptimize`, connection persistence, pooling and leftover sampled statistics: all 224 + matched the expected rows, schema and metadata, and the next launch wrote nothing. +- The process killed at random and at each step of the swap on a copy of the 2.37 GB store, + with a writer running: no acknowledged write lost, `quick_check` clean, the next call + finished the work. +- Disk full before and during the copy, and each step of the swap made to fail, including + the reopen: nothing lost, and the instance serving or recovered by `Connect`. +- iOS simulator and an Android emulator (API 35), .NET 10: `DriveInfo`, the swap, the file + mode, and reads and writes during `Optimize`. +- Code compiled against 5.3.1 runs against this build. diff --git a/docs/planner-statistics-sampling.sql b/docs/planner-statistics-sampling.sql new file mode 100644 index 0000000..a409c22 --- /dev/null +++ b/docs/planner-statistics-sampling.sql @@ -0,0 +1,136 @@ +-- 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. +-- +-- 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] 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 +.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; + +-- 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;' +.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 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') = 'missing'); +.timer off + +-- --------------------------------------------------------------------------- +.print +.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 '-- 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') = '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 '== [3] Full statistics, for comparison: 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 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 '== [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; +PRAGMA optimize; +SELECT 'stat1: ' || idx || ' -> ' || stat FROM sqlite_stat1 WHERE tbl = 'JsonValue' ORDER BY idx; +.print '-- plan:' +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 From fadbd96beb4d1dbe5055ad77bfcd533a3553255f Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Fri, 6 Nov 2026 16:39:28 -0600 Subject: [PATCH 08/11] fix: clear the connection pool before rebuildCache deletes the file --- CHANGELOG.md | 4 +++ TychoDB.UnitTests/ConnectionLifecycleTests.cs | 33 +++++++++++++++++++ TychoDB/Tycho.cs | 14 +++++--- 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce04b9a..52c15b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,10 @@ throws `ObjectDisposedException`. - **A connection whose setup failed kept the file locked** until the finalizer ran, so the retry got `database is locked`. It is disposed before the failure propagates. +- **`rebuildCache` could leave an instance on the deleted file.** After a `Dispose` in the + same process the pool kept the old connection, and the next `Connect` got it back: the + instance saw the old rows, and every write it acknowledged went with the deleted file. The + pool is now cleared before the delete. ### Added diff --git a/TychoDB.UnitTests/ConnectionLifecycleTests.cs b/TychoDB.UnitTests/ConnectionLifecycleTests.cs index 16b7673..7c07aa6 100644 --- a/TychoDB.UnitTests/ConnectionLifecycleTests.cs +++ b/TychoDB.UnitTests/ConnectionLifecycleTests.cs @@ -130,4 +130,37 @@ private static List> StartReads(Tycho db) } })) .ToList(); + + [DataTestMethod] + [DataRow(true)] + [DataRow(false)] + public async Task RebuildCache_AfterADispose_WritesToTheNewFile(bool persistConnection) + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = NewInstance(path, dbName, persistConnection, rebuildCache: false).Connect()) + { + await db.WriteObjectAsync(new Item { Key = "item-old", Group = "G0", Seq = 1 }, x => x.Key); + } + + using (var db = NewInstance(path, dbName, persistConnection, rebuildCache: true).Connect()) + { + (await db.CountObjectsAsync()).ShouldBe(0); + + await db.WriteObjectAsync(new Item { Key = "item-new", Group = "G0", Seq = 2 }, x => x.Key); + } + + File.Exists(dbFile).ShouldBeTrue(); + ReadScalar(dbFile, "SELECT COUNT(*) FROM JsonValue").ShouldBe(1); + } + + private static Tycho NewInstance(string path, string dbName, bool persistConnection, bool rebuildCache) + { +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: persistConnection, rebuildCache: rebuildCache, requireTypeRegistration: false); +#else + return new Tycho(path, Serializer, dbName, persistConnection: persistConnection, rebuildCache: rebuildCache, requireTypeRegistration: false); +#endif + } } diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 2affd1f..766ce60 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -165,11 +165,6 @@ public Tycho( string databasePath = Path.Join(dbPath, dbName); - if (rebuildCache && File.Exists(databasePath)) - { - File.Delete(databasePath); - } - var connectionStringBuilder = new SqliteConnectionStringBuilder { @@ -191,6 +186,15 @@ public Tycho( connectionStringBuilder.Pooling = useConnectionPooling; _dbConnectionString = connectionStringBuilder.ToString(); + + if (rebuildCache && File.Exists(databasePath)) + { + using var pooledConnections = new SqliteConnection(_dbConnectionString); + + SqliteConnection.ClearPool(pooledConnections); + File.Delete(databasePath); + } + _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; _autoOptimize = autoOptimize; From 801de07711f22963b98e56a461be851a9cd435bd Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 28 Nov 2026 00:28:04 -0600 Subject: [PATCH 09/11] docs: say Cleanup(vacuum: true) also replaces the file and drops its attributes --- README.md | 8 +++++--- TychoDB/Tycho.cs | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4e88d00..4561239 100644 --- a/README.md +++ b/README.md @@ -535,9 +535,11 @@ This matters for how they behave: been told about. It returns `false` when work remains for a later call, such as when the disk lacks room for the copy, and it is free once there is nothing left to do, so calling it on every launch is fine. -- **Compaction replaces the database file.** Its permissions carry over. Anything else - your app set on the file, such as an iOS backup exclusion or a file protection class, - does not, so set it again after the first `Optimize()`. Keep to one `Tycho` instance per +- **Compaction replaces the database file.** `Optimize()` and `Cleanup(vacuum: true)` both + compact a store that has no incremental auto-vacuum. The file's permissions carry over. + Anything else your app set on it, such as an iOS backup exclusion or a file protection + class, does not, so set it again after the first compaction, or put a backup exclusion + on the store's folder, which the swap leaves in place. Keep to one `Tycho` instance per file, with `persistConnection: false` too: a connection that has the file open without holding a lock, such as one still connecting, cannot be detected, and after the swap it can lose what it writes. Nothing shrinks the file on the default path until you call diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 766ce60..0208799 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -3248,9 +3248,11 @@ private static long ReadPragma(SqliteConnection conn, string pragma) /// 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 ). Either way - /// the work does runs first, in the same steps, so that the - /// indexes it replaces are not copied. + /// is skipped when the space is not there (see ). The swap + /// replaces the file, so attributes set on it other than its permissions, such as a + /// backup exclusion or a file protection class, do not carry over. Either way the work + /// does runs first, in the same steps, so that the indexes it + /// replaces are not copied. /// public void Cleanup(bool shrinkMemory = true, bool vacuum = false) { From 8688ca5c087e0a44f4577dab983a33481948d732 Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 28 Nov 2026 16:58:25 -0600 Subject: [PATCH 10/11] docs: correct what Optimize does on a disconnected instance, the longest wait, and unsorted read order --- CHANGELOG.md | 14 ++++++++++---- README.md | 17 ++++++++++------- TychoDB/Tycho.cs | 3 ++- docs/planner-statistics-sampling.md | 3 ++- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52c15b6..107c7b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -94,14 +94,20 @@ transaction, so an interruption leaves one or the other), and return the freed pages to the file system. Every other operation runs between steps, so a call waits for the step in progress, never for the whole of it: about 20 s in all on that store, with reads and - writes running throughout, none failing, and none waiting more than about 4 s. `Optimize()` - runs on the calling thread, so call it from a background thread; `OptimizeAsync()` runs - only its first step there, and its token is observed between steps. Both return true when + writes running throughout, none failing, and none waiting more than about 4 s. In an app + with 2.6–3.1 GB stores, reads waited up to 11 s and writes up to 7 s. `Optimize()` runs + on the calling thread, so call it from a background thread; `OptimizeAsync()` runs only + its first step there, and its token is observed between steps. Both return true when nothing is left to do and false when work remains for a later call: the volume lacks the space, the file or a blob stream of this instance is in use, or the instance was - disconnected. Idempotent: with nothing to do they read the schema and write nothing, so + disconnected or disposed during the call. Called on an instance that is not connected, + they throw. Idempotent: with nothing to do they read the schema and write nothing, so calling them on every launch is fine. + Once a store's indexes are replaced or the store is compacted, a read without a sort can + return the same rows in another order, and rows with equal sort values can swap. Pass a + sort where the order matters. + A store with incremental auto-vacuum reclaims in place when at least a tenth of the file is free. One without it — every 4.x store, whose connect script set the pragma too late — is compacted: the live pages are written into a copy next to the database with `VACUUM diff --git a/README.md b/README.md index 4561239..15d726a 100644 --- a/README.md +++ b/README.md @@ -528,13 +528,13 @@ This matters for how they behave: that has no incremental auto-vacuum (every 4.x store): the live pages are written into a copy next to the database with `VACUUM INTO`, the copy is flushed to disk, and it is renamed over the file. It took about 20 s on that store, which went from 2.37 GB to - 1.04 GB. Other operations run between steps, so a call waits for the step in progress, - about 4 s at the longest on that store on a Mac and longer on a phone, rather than for - all of it. Interrupt it at any point and the store still works; the next call goes on - from there. Call it after declaring your indexes: it only builds what this instance has - been told about. It returns `false` when work remains for a later call, such as when - the disk lacks room for the copy, and it is free once there is nothing left to do, so - calling it on every launch is fine. + 1.04 GB. Other operations run between steps, so a call waits for the step in progress + rather than for all of it: about 4 s at the longest on that store on a Mac, up to 11 s + on 2.6 to 3.1 GB stores in an app, and longer on a phone. Interrupt it at any point and + the store still works; the next call goes on from there. Call it after declaring your + indexes: it only builds what this instance has been told about. It returns `false` when + work remains for a later call, such as when the disk lacks room for the copy, and it is + free once there is nothing left to do, so calling it on every launch is fine. - **Compaction replaces the database file.** `Optimize()` and `Cleanup(vacuum: true)` both compact a store that has no incremental auto-vacuum. The file's permissions carry over. Anything else your app set on it, such as an iOS backup exclusion or a file protection @@ -544,6 +544,9 @@ This matters for how they behave: holding a lock, such as one still connecting, cannot be detected, and after the swap it can lose what it writes. Nothing shrinks the file on the default path until you call `Optimize()` or `Cleanup(vacuum: true)`. +- **Unsorted reads can change order.** Once a store's indexes are replaced or the store is + compacted, a read without a sort can return the same rows in another order, and rows + with equal sort values can swap. Pass a `SortBuilder` where the order matters. - **The upgrade pays back on every write.** With the whole-table 4.x indexes gone, 50,000-row bulk writes on a 1.8M-row, 3 GB 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 diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 0208799..c44a091 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -2817,7 +2817,8 @@ public IReadOnlyList ListIndexes() /// /// True when nothing is left to do. False when work remains for a later call: the /// volume lacks the free space for the compacted copy or for a rebuild, the file or a - /// blob stream of this instance is in use, or the instance was disconnected or disposed. + /// blob stream of this instance is in use, or the instance was disconnected or disposed + /// during the call. Called on an instance that is not connected, it throws. /// public bool Optimize() { diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md index 2c14077..6b853d5 100644 --- a/docs/planner-statistics-sampling.md +++ b/docs/planner-statistics-sampling.md @@ -171,7 +171,8 @@ covers another property is built at once. compaction that returns the freed pages — 1.3 GB on that store — since a 4.x store has no incremental auto-vacuum and nothing else can. Each is a step that takes the gate on its own, so other operations run between steps and wait only for the step in progress, about 4 s at -the longest on that store. The compaction is one step: nothing can write during the copy. +the longest on that store and up to 11 s on 2.6–3.1 GB stores in an app. The compaction is +one step: nothing can write during the copy. The compaction is `VACUUM INTO` a copy next to the database, then a swap: the copy is flushed to disk and takes the file's permissions, the connection closes, the copy is renamed From 3f129cce33e27fa0b124803dbeadec6431232b4e Mon Sep 17 00:00:00 2001 From: AJ Rotolo Date: Sat, 28 Nov 2026 17:19:34 -0600 Subject: [PATCH 11/11] docs: keep declaring an index 4.x built until its store has been upgraded --- CHANGELOG.md | 6 ++++++ README.md | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 107c7b6..bbb104b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,12 @@ after declaring them. Without it a 4.x store keeps its old indexes and its size and otherwise behaves as it did. + An index 4.x built is found only through its declaration, with `autoOptimize` on or off. + One whose `CreateIndex` call has been removed from the app is not dropped by connect or by + `Optimize()`, is copied by the compaction, and makes `DropIndex` return false, since + nothing records it. Keep the declaration until the store has been upgraded; `DropIndex` + then removes the index. + `Optimize()` / `OptimizeAsync()` do the work in steps: delete leftover statistics, drop each of the four indexes, build each deferred index and drop what it replaces (in one transaction, so an interruption leaves one or the other), and return the freed pages to diff --git a/README.md b/README.md index 15d726a..034aee2 100644 --- a/README.md +++ b/README.md @@ -535,6 +535,13 @@ This matters for how they behave: indexes: it only builds what this instance has been told about. It returns `false` when work remains for a later call, such as when the disk lacks room for the copy, and it is free once there is nothing left to do, so calling it on every launch is fine. +- **Keep declaring an index 4.x built until its store has been upgraded.** TychoDB finds + that index only through the `CreateIndex` call that declares it, with `autoOptimize` on + or off. Take the call out first and the old index stays: neither connect nor `Optimize()` + drops it, the compaction copies it, and `DropIndex` returns `false`, because nothing + records it. It is a whole-table index, so every write goes on maintaining it. Once the + store has been upgraded with the declaration in place, the index is a recorded one and + `DropIndex` removes it. - **Compaction replaces the database file.** `Optimize()` and `Cleanup(vacuum: true)` both compact a store that has no incremental auto-vacuum. The file's permissions carry over. Anything else your app set on it, such as an iOS backup exclusion or a file protection