diff --git a/CHANGELOG.md b/CHANGELOG.md index 117fd5d..3e8bbf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,107 @@ # 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, as the `PRAGMA optimize` it replaces was: a store on a read-only file or a + full volume still connects, with the planner misled until a connect that can write, while + `Optimize()` reports the failure. The one thing statistics could add — ranking two + single-property indexes when a filter ANDs both — is what a composite index is for. +- **The string overload of `CreateIndex` silently kept the index 4.x built.** It names its + index exactly as 4.x did, so its `CREATE INDEX IF NOT EXISTS` met the 4.x index and did + nothing, while the metadata recorded the new definition as built: queries still matched + the old `(FullTypeName, expr)` shape, but the index carried every type's rows and the + metadata lied for good. `CreateIndex` now compares the stored DDL of a same-named index + with the definition it wants and rebuilds on a mismatch — on the spot, or through + `Optimize()` under `autoOptimize: false` — which also repairs the stores earlier 5.x + releases recorded that way. +- **A 4.x rollback left its per-type indexes behind for good.** After 5.x → 4.x → 5.x, + 4.x had recreated `idx__` next to the 5.x `idx___`, and the + re-declaration found its own index current and never looked at the legacy name, so both + were maintained on every write and the planner could prefer the wider one. `CreateIndex` + now probes the legacy name on the current path and drops it (left to `Optimize()` under + `autoOptimize: false`), `Optimize()` sweeps it for every recorded index, and `DropIndex` + drops it together with the index. A legacy name that another declaration records as its + own index is left alone by all three: the string overload names its index exactly as 4.x + did, so an app declaring one name through both overloads keeps both indexes instead of + dropping and rebuilding the string overload's on every launch. +- **Connecting to an existing store wrote page 1 every time.** `PRAGMA auto_vacuum = + INCREMENTAL` only takes effect on a database being created, but on an auto-vacuum store + it stores the mode the file already has, in a write transaction that bumps the change + counter. It now runs only for a new or empty file, so connecting to a current store + writes nothing: the file is byte-identical afterwards. + +### Added + +- **`autoOptimize` constructor parameter (default `true`), `Optimize()` and + `OptimizeAsync()`.** 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.8M-row, + 3 GB store, and most of a 10–30 s first launch measured in an app on device, since + freeing an index's pages takes time proportional to its size and SQLCipher's default + `secure_delete` writes every freed page back — and the first `CreateIndex` for each + declaration drops the whole-table index 4.x built for it and builds the partial one + (0.7–4.7 s each on that store, 9 s for six). Pass `autoOptimize: false` to defer both: + connect leaves the indexes in place, and `CreateIndex` records the declaration as + pending (`ShapeVersion 0` in `TychoIndex`) while queries keep using the index 4.x built + — connect and six declarations then take about 140 ms on that store; a declaration no + existing index serves is built at once either way. `Optimize()` / `OptimizeAsync()` + then do, in one hold of the connection: the four drops, every pending rebuild (each in a + transaction of its own, so an interruption leaves either the old index or the new one), + the orphan drops a rollback needs, the statistics delete, and a compaction when the + store has no incremental auto-vacuum — every 4.x store, whose connect script set the + pragma too late — or an in-place `incremental_vacuum` when at least a tenth of the file + is free. The compaction rewrites the live pages into a copy next to the database with + `VACUUM INTO`, closes the connection, renames the copy over the file and reopens on it: + it converts the store, returns the freed pages to the file system (3.06 GB → 1.03 GB on + that store, 2.37 GB → 1.04 GB on a 1.76M-row one), needs free disk space for the + compacted copy only — a full `VACUUM` writes the data twice, to a temp copy and back + through the WAL, and failed with the disk full where this succeeds — and leaves the + database untouched until the rename, which is atomic; the WAL is deleted before the + rename, since SQLite checks a WAL only against its own header and would replay a leftover + one into the new file, so an interruption costs at most a leftover copy the next call + removes. It is skipped, to be retried by the next call, when + the volume lacks the space, SQLite reports it full, or the WAL survives the close + because the close could not checkpoint it; under SQLCipher the drops run with + `secure_delete` off when a compaction follows, since the setting otherwise zeroes every + freed page through the WAL and the drops need free space equal to the index. With the + whole-table 4.x indexes gone, 50,000-row bulk writes on that store ran 2.1x faster for + an indexed type (38k → 80k rows/s) and 3x for an unindexed one (62k → 190k rows/s), and + partition deletes 2.2–2.7x; none of the timings changed with the file cold on disk. + Idempotent: with nothing pending they read the schema and write nothing, so calling them + on every launch is fine. They hold the single connection for the duration, so every + other operation on the instance waits, and run on the calling thread — + Microsoft.Data.Sqlite executes synchronously, so `OptimizeAsync` alone does not move the + work off the caller — so call them from a background thread. `Cleanup(vacuum: true)` + compacts a store without incremental auto-vacuum the same way. `ListIndexes()` lists a + pending index with the definition it will get. A pending definition is read back out of + the file before it runs, so `Optimize()` re-checks it rather than trusting it: the + statement is taken apart into the paths and type it indexes and must build again byte + for byte, and one that does not — a second statement appended, an expression TychoDB + never emits — is refused with a `TychoException` naming the index, the store left as it + was. + ## 5.3.1 — 2026-10-05 ### 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..0fc7565 100644 --- a/README.md +++ b/README.md @@ -492,12 +492,41 @@ 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. +- **Upgrading a store from 4.x costs tens of seconds, once:** connecting drops the four + redundant indexes 4.x created (9 s on a 1.8M-row, 3 GB store), and the first + `CreateIndex` for each declaration drops the whole-table index 4.x built for it and + builds the partial one (9 s for six). Both run on the calling thread. Pass + `autoOptimize: false` to defer both: connect and the declarations then cost about + 140 ms, `CreateIndex` records each declaration as pending while queries keep using the + index 4.x built, and `Optimize()` / `OptimizeAsync()` — called from a background + thread — do the drops, the rebuilds, and a compaction that returns the freed pages to + the file system (3.06 GB to 1.03 GB on that store): the live pages are written into a + copy next to the database with `VACUUM INTO` and the copy is swapped in, so the free + space needed is the compacted copy, the file is untouched until an atomic rename, and + the step is skipped and retried next time when the space is not there. A declaration no + existing index serves is built at once either way. +- **The upgrade pays back on every write.** With the whole-table 4.x indexes gone, + 50,000-row bulk writes on that store ran 2.1x faster for an indexed type (38k to 80k + 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 +570,15 @@ 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); +await deferredDb.ConnectAsync(); +deferredDb.CreateIndex(x => x.Age, "age_index"); +await Task.Run(() => deferredDb.Optimize()); ``` ### Device Performance Profiles @@ -593,6 +631,14 @@ await db.DeleteObjectsAsync(); ```csharp // Optimize database performance and reduce size 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. Holds the connection for the duration — every other operation on this instance +// waits; tens of seconds on a 1.8M-row, 3 GB store upgraded from 4.x — and runs on the +// calling thread, so call it from a background thread, never the UI thread. +await Task.Run(() => db.Optimize()); ``` ## LINQ Support 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..5a9376c 100644 --- a/TychoDB.UnitTests/ConfigurationTests.cs +++ b/TychoDB.UnitTests/ConfigurationTests.cs @@ -59,6 +59,17 @@ public void AutoVacuum_IsSetBeforeJournalMode() autoVacuumIndex.ShouldBeLessThan(journalModeIndex, "auto_vacuum must be set before journal_mode = WAL"); } + [TestMethod] + public void ExistingDatabaseScript_OmitsTheCreationOnlyAutoVacuumPragma() + { + // On an auto-vacuum store the pragma rewrites page 1 at every connect for nothing, + // so a file that already exists is opened without it. + var script = Queries.BuildConnectionScript(TychoPerformanceProfile.Mobile, newDatabase: false); + + script.ShouldNotContain("PRAGMA auto_vacuum"); + script.ShouldContain("PRAGMA journal_mode = WAL;"); + } + [TestMethod] public async Task FreshDatabase_IsCreatedWithIncrementalAutoVacuum() { diff --git a/TychoDB.UnitTests/IndexDdlTests.cs b/TychoDB.UnitTests/IndexDdlTests.cs index 4576e26..0b9a531 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); @@ -510,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() { @@ -645,6 +687,32 @@ public async Task DroppedIndex_CanBeRecreated() /// Physical index names carry a hash suffix of the full type name, so tests /// locate an index by its logical name prefix rather than an exact key. /// + [TestMethod] + public void IndexDefinition_IsAcceptedOnlyAsBuilt() + { + const string name = "idx_seq_idx_Item_0a1b2c3d"; + var paths = new[] { ("$.Seq", true), ("$.Nested.Name", false), ("$.Tags[0]", false) }; + + var partial = Queries.CreateIndexForJsonValue(name, paths, typeof(IndexTestModel).FullName); + var quoted = Queries.CreateIndexForJsonValue(name, paths, "Ns.O'Brien+Item"); + var manual = Queries.CreateIndexForJsonValue(name, paths); + + Queries.IsIndexDefinitionFor(partial, name).ShouldBeTrue(); + Queries.IsIndexDefinitionFor(quoted, name).ShouldBeTrue(); + Queries.IsIndexDefinitionFor(manual, name).ShouldBeTrue(); + + Queries.IsIndexDefinitionFor(partial, "idx_seq_idx_Item").ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial + " DROP TABLE StreamValue;", name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.TrimEnd(';'), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(manual + " DROP TABLE StreamValue;", name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(manual.Replace(");", "); DROP TABLE StreamValue; --", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("WHERE FullTypeName = '", "WHERE FullTypeName = ''; DROP TABLE StreamValue; --", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("$.Seq", "$.Seq') as NUMERIC)); DROP TABLE StreamValue; --", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("JsonValue(", "StreamValue(", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor(partial.Replace("JSON_EXTRACT(Data, '$.Nested.Name')", "lower(JSON_EXTRACT(Data, '$.Nested.Name'))", StringComparison.Ordinal), name).ShouldBeFalse(); + Queries.IsIndexDefinitionFor($"CREATE INDEX IF NOT EXISTS {name}\nON JsonValue(Partition)\nWHERE FullTypeName = 'X';", name).ShouldBeFalse(); + } + private static string Find(Dictionary ddl, string logicalIndexName) { var prefix = $"idx_{logicalIndexName}_"; @@ -714,13 +782,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..48c1612 --- /dev/null +++ b/TychoDB.UnitTests/OptimizeTests.cs @@ -0,0 +1,864 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TychoDB; + +namespace TychoDB.UnitTests; + +/// +/// Proves the upgrade path a store takes from 4.x and the work Optimize does for it: +/// under autoOptimize: false a declaration whose index 4.x built is recorded as pending +/// and served by that index until Optimize rebuilds it; the string overload's +/// same-named 4.x index is recognised as stale instead of kept; the index a 4.x rollback +/// leaves next to a current one is dropped, while one another declaration records as its +/// own is kept; a current store is never written to by connect, by a declaration, or by +/// Optimize; a store on a read-only file still connects; and a pending definition +/// that is not the statement Tycho built is refused rather than run. +/// +[TestClass] +public class OptimizeTests +{ +#if ENCRYPTED + private const string DbPassword = "Password"; +#endif + + private const string IndexName = "seq_idx"; + private const string LegacyIndexName = "idx_seq_idx_Item"; + private const string ManualIndexName = "manual_idx"; + private const string ManualPhysicalName = "idx_manual_idx_Item"; + private const string GeneralIndexName = "idx_jsonvalue_fulltypename_partition"; + + private const long LookupSeq = 42; + + private static readonly string[] BuiltInLegacyIndexNames = + { + "idx_jsonvalue_fulltypename", + "idx_jsonvalue_key_fulltypename", + "idx_jsonvalue_key_fulltypename_partition", + "idx_streamvalue_key_partition", + }; + + private static readonly IJsonSerializer Serializer = new NewtonsoftJsonSerializer(); + + public class Item + { + public string Key { get; set; } + + public string Group { get; set; } + + public long Seq { get; set; } + } + + private readonly record struct MetadataRow( + string IndexName, + string FullTypeName, + string PhysicalName, + string Definition, + long ShapeVersion); + + [TestMethod] + public async Task LegacyStore_WithAutoOptimizeOff_DefersTheRebuildToOptimize() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + long schemaVersion = ReadPragma(dbFile, "schema_version"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + // Recorded as pending: no DDL ran, the 4.x index still serves the lookup. + var ddl = ReadIndexDdl(dbFile); + ddl[LegacyIndexName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + ddl.Keys.ShouldNotContain(k => k.StartsWith(LegacyIndexName + "_", StringComparison.Ordinal)); + ddl.Keys.ShouldContain("idx_jsonvalue_fulltypename"); + + var pending = ReadMetadata(dbFile).ShouldHaveSingleItem(); + pending.IndexName.ShouldBe(IndexName); + pending.FullTypeName.ShouldBe(typeof(Item).FullName); + pending.PhysicalName.ShouldStartWith(LegacyIndexName + "_"); + pending.Definition.ShouldContain("WHERE FullTypeName", Case.Sensitive); + pending.ShapeVersion.ShouldBe(0); + + var plan = ExplainLookup(dbFile); + plan.ShouldContain(LegacyIndexName, Case.Sensitive); + plan.ShouldNotContain(LegacyIndexName + "_", Case.Sensitive); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(0); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + await AssertLookup(db); + } + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[pending.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + ddl.ShouldContainKey(GeneralIndexName); + + foreach (var name in BuiltInLegacyIndexNames) + { + ddl.ShouldNotContainKey(name); + } + + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + ExplainLookup(dbFile).ShouldContain(pending.PhysicalName, Case.Sensitive); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + + // Done once: declaring and optimizing again touch nothing. + var hash = FileHash(dbFile); + schemaVersion = ReadPragma(dbFile, "schema_version"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + } + + FileHash(dbFile).ShouldBe(hash); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + } + + [TestMethod] + public async Task LegacyStore_WithAutoOptimizeOn_RebuildsOnDeclaration() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.ShapeVersion.ShouldBe(2); + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[row.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + + foreach (var name in BuiltInLegacyIndexNames) + { + ddl.ShouldNotContainKey(name); + } + + ExplainLookup(dbFile).ShouldContain(row.PhysicalName, Case.Sensitive); + } + + [TestMethod] + public async Task NewIndex_WithAutoOptimizeOff_IsBuiltAtOnce() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + } + + // Nothing in the schema serves the declaration, so deferring it would leave the + // lookup without an index. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.ShapeVersion.ShouldBe(2); + ReadIndexDdl(dbFile).ShouldContainKey(row.PhysicalName); + ExplainLookup(dbFile).ShouldContain(row.PhysicalName, Case.Sensitive); + } + + [TestMethod] + public async Task RolledBackStore_OrphanLegacyIndex_IsDropped() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var current = ReadMetadata(dbFile).ShouldHaveSingleItem(); + var currentSql = ReadIndexDdl(dbFile)[current.PhysicalName]; + + // 4.x reopened the store and built its own index for the same declaration. + Execute(dbFile, LegacyIndexDdl(LegacyIndexName)); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + + // Declared again with autoOptimize off: the orphan is left for Optimize. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + await AssertLookup(db); + } + + var ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[current.PhysicalName].ShouldBe(currentSql); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(current); + + // Declared again with autoOptimize on: dropped on the spot. + Execute(dbFile, LegacyIndexDdl(LegacyIndexName)); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + } + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldNotContainKey(LegacyIndexName); + ddl[current.PhysicalName].ShouldBe(currentSql); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(current); + } + + [TestMethod] + public async Task StringOverload_SameNamedLegacyIndex_IsRecognisedAsStale() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + } + + // 4.x built its index under the very name the string overload uses. + Execute(dbFile, LegacyIndexDdl(ManualPhysicalName)); + + // autoOptimize off: recorded as pending, the 4.x index left to serve queries. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", ManualIndexName); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + + var pending = ReadMetadata(dbFile).ShouldHaveSingleItem(); + pending.IndexName.ShouldBe(ManualIndexName); + pending.FullTypeName.ShouldBe("Item"); + pending.PhysicalName.ShouldBe(ManualPhysicalName); + pending.ShapeVersion.ShouldBe(0); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + + // Earlier 5.x releases recorded the declaration as current over the 4.x index, + // which CREATE INDEX IF NOT EXISTS had silently kept. autoOptimize on rebuilds it. + Execute(dbFile, $"DROP INDEX {ManualPhysicalName}; " + LegacyIndexDdl(ManualPhysicalName)); + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, CAST", Case.Sensitive); + + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", ManualIndexName); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile)[ManualPhysicalName].ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + + [TestMethod] + public async Task CurrentStore_ConnectDeclareAndOptimize_WriteNothing() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Group", isNumeric: false, "Item", ManualIndexName); + } + + var hash = FileHash(dbFile); + long schemaVersion = ReadPragma(dbFile, "schema_version"); + + foreach (var autoOptimize in new[] { true, false }) + { + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Group", isNumeric: false, "Item", ManualIndexName); + db.Optimize(); + await AssertLookup(db); + } + + FileHash(dbFile).ShouldBe(hash); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + } + } + + [TestMethod] + public async Task LegacyStore_Optimize_SwapsInTheCompactedCopy_AndKeepsServingOnIt() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + var compactedFile = dbFile + Queries.CompactedFileSuffix; + + // A copy an interrupted run left behind is replaced, not reused. + File.WriteAllText(compactedFile, "not a database"); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + + // The instance works on the swapped-in file without reconnecting: the + // lookup, a write, and a read of that write all go through it. + await AssertLookup(db); + await db.WriteObjectAsync(new Item { Key = "item-new", Group = "G0", Seq = 1000 }, x => x.Key); + (await db.ReadObjectAsync("item-new")).ShouldNotBeNull().Seq.ShouldBe(1000); + (await db.CountObjectsAsync()).ShouldBe(101); + } + + File.Exists(compactedFile).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadPragma(dbFile, "freelist_count").ShouldBe(0); + ReadText(dbFile, "PRAGMA journal_mode").ShouldBe("wal"); + ReadScalar(dbFile, "SELECT COUNT(*) FROM JsonValue").ShouldBe(101); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + + // Reopened from scratch, the store is the compacted one. + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(101); + } + } + + [TestMethod] + public async Task LegacyStore_Optimize_WithoutAPersistentConnection_Compacts() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false, persistConnection: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + db.Optimize(); + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(100); + } + + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + + [TestMethod] + public async Task LegacyStore_Cleanup_CompactsThroughTheSameSwap() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Cleanup(shrinkMemory: true, vacuum: true); + (await db.CountObjectsAsync()).ShouldBe(100); + } + + File.Exists(dbFile + Queries.CompactedFileSuffix).ShouldBeFalse(); + ReadPragma(dbFile, "auto_vacuum").ShouldBe(2); + ReadText(dbFile, "PRAGMA journal_mode").ShouldBe("wal"); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + } + + [TestMethod] + public async Task Connect_DeletesLeftoverStatisticsOnce_ThenLeavesTheEmptyTableAlone() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'sqlite_stat1'").ShouldBe(0); + + Execute(dbFile, "ANALYZE;"); + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBeGreaterThan(0); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(0); + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'sqlite_stat1'").ShouldBe(1); + + var hash = FileHash(dbFile); + + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + FileHash(dbFile).ShouldBe(hash); + } + + [TestMethod] + public async Task BothOverloads_UnderOneName_LeaveEachOthersIndexAlone() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + // The string overload names its index exactly as 4.x did: the generic overload's + // legacy name. Declared second, the generic index must not take it for an orphan. + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", IndexName); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var rows = ReadMetadata(dbFile); + rows.Count.ShouldBe(2); + rows.ShouldAllBe(r => r.ShapeVersion == 2); + + var manual = rows.Single(r => r.PhysicalName == LegacyIndexName); + var generic = rows.Single(r => r.PhysicalName != LegacyIndexName); + manual.FullTypeName.ShouldBe("Item"); + generic.FullTypeName.ShouldBe(typeof(Item).FullName); + generic.PhysicalName.ShouldStartWith(LegacyIndexName + "_"); + + var ddl = ReadIndexDdl(dbFile); + ddl[LegacyIndexName].ShouldContain("ON JsonValue(FullTypeName, Partition, CAST", Case.Sensitive); + ddl[generic.PhysicalName].ShouldContain("WHERE FullTypeName", Case.Sensitive); + + // Every later launch finds both current and touches nothing, in either order. + var hash = FileHash(dbFile); + long schemaVersion = ReadPragma(dbFile, "schema_version"); + + foreach (var autoOptimize in new[] { true, false }) + { + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + await db.CreateIndexAsync("$.Seq", isNumeric: true, "Item", IndexName); + db.Optimize(); + await AssertLookup(db); + } + + FileHash(dbFile).ShouldBe(hash); + ReadPragma(dbFile, "schema_version").ShouldBe(schemaVersion); + } + + // Dropping the generic declaration leaves the string overload's index and row. + using (var db = await BuildDb2(path, dbName).ConnectAsync()) + { + db.DropIndex(IndexName).ShouldBeTrue(); + await AssertLookup(db); + } + + ddl = ReadIndexDdl(dbFile); + ddl.ShouldContainKey(LegacyIndexName); + ddl.ShouldNotContainKey(generic.PhysicalName); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShouldBe(manual); + } + + [TestMethod] + public async Task Connect_OnAReadOnlyFile_LeavesTheStatisticsAndSucceeds() + { + if (OperatingSystem.IsWindows()) + { + Assert.Inconclusive("Unix file modes are used to make the file read-only."); + } + + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + Execute(dbFile, "ANALYZE;"); + long statisticsRows = ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1"); + statisticsRows.ShouldBeGreaterThan(0); + + SqliteConnection.ClearAllPools(); + var mode = File.GetUnixFileMode(dbFile); + File.SetUnixFileMode(dbFile, UnixFileMode.UserRead | UnixFileMode.GroupRead | UnixFileMode.OtherRead); + + try + { + if (CanOpenForWriting(dbFile)) + { + Assert.Inconclusive("The file stays writable for this user, so the read-only connect cannot be exercised."); + } + + foreach (var autoOptimize in new[] { true, false }) + { + using var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync(); + await db.CreateIndexAsync(x => x.Seq, IndexName); + await AssertLookup(db); + (await db.CountObjectsAsync()).ShouldBe(100); + } + } + finally + { + // SQLite gives the -wal and -shm it creates the database file's mode. + SqliteConnection.ClearAllPools(); + + foreach (var file in new[] { dbFile, dbFile + "-wal", dbFile + "-shm" }.Where(File.Exists)) + { + File.SetUnixFileMode(file, mode); + } + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(statisticsRows); + + // Writable again, the next connect deletes them. + using (await BuildDb2(path, dbName).ConnectAsync()) + { + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_stat1").ShouldBe(0); + } + + [TestMethod] + public async Task Optimize_RefusesATamperedPendingDefinition() + { + var dbFile = await SeedLegacyStore(); + var (path, dbName) = Split(dbFile); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + await db.CreateIndexAsync(x => x.Seq, IndexName); + } + + var pending = ReadMetadata(dbFile).ShouldHaveSingleItem(); + pending.ShapeVersion.ShouldBe(0); + + // Each keeps the prefix and the name Tycho wrote and carries a second statement: + // after the column list, and inside the type literal of the WHERE clause. + var tampered = new[] + { + $"CREATE INDEX IF NOT EXISTS {pending.PhysicalName}\nON JsonValue(Partition); DROP TABLE StreamValue; --", + pending.Definition.Replace("WHERE FullTypeName = '", "WHERE FullTypeName = ''; DROP TABLE StreamValue; --", StringComparison.Ordinal), + }; + + foreach (var definition in tampered) + { + definition.ShouldContain("DROP TABLE", Case.Sensitive); + WriteDefinition(dbFile, definition); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + Should.Throw(() => db.Optimize()).Message.ShouldContain(IndexName, Case.Sensitive); + await AssertLookup(db); + } + + ReadScalar(dbFile, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'StreamValue'").ShouldBe(1); + ReadIndexDdl(dbFile).ShouldContainKey(LegacyIndexName); + ReadIndexDdl(dbFile).ShouldNotContainKey(pending.PhysicalName); + + var row = ReadMetadata(dbFile).ShouldHaveSingleItem(); + row.ShapeVersion.ShouldBe(0); + row.Definition.ShouldBe(definition); + } + + // The definition as Tycho wrote it is built. + WriteDefinition(dbFile, pending.Definition); + + using (var db = await BuildDb2(path, dbName, autoOptimize: false).ConnectAsync()) + { + db.Optimize(); + await AssertLookup(db); + } + + ReadIndexDdl(dbFile).ShouldContainKey(pending.PhysicalName); + ReadMetadata(dbFile).ShouldHaveSingleItem().ShapeVersion.ShouldBe(2); + } + + // ---------- seeding ---------- + + /// + /// A store as 4.4.2 leaves it: its per-type index for Seq under the legacy name and + /// shape, its four built-in indexes, no index metadata, and no incremental auto-vacuum. + /// + private static async Task SeedLegacyStore() + { + var (path, dbName) = NewDbPath(); + var dbFile = Path.Combine(path, dbName); + + using (var db = await BuildDb(path, dbName).ConnectAsync()) + { + await db.WriteObjectsAsync(Items(), x => x.Key); + } + + var legacySchema = + LegacyIndexDdl(LegacyIndexName) + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_fulltypename ON JsonValue (FullTypeName);" + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_key_fulltypename ON JsonValue (Key, FullTypeName);" + + "CREATE INDEX IF NOT EXISTS idx_jsonvalue_key_fulltypename_partition ON JsonValue (Key, FullTypeName, Partition);" + + "CREATE INDEX IF NOT EXISTS idx_streamvalue_key_partition ON StreamValue (Key, Partition);" + + "DELETE FROM TychoIndex;" + + "PRAGMA auto_vacuum = NONE; VACUUM;"; + + Execute(dbFile, legacySchema); + + ReadPragma(dbFile, "auto_vacuum").ShouldBe(0); + ReadMetadata(dbFile).ShouldBeEmpty(); + + return dbFile; + } + + /// The DDL 4.4.2 ran for CreateIndex<Item>(x => x.Seq, …): whole-table, led by FullTypeName. + private static string LegacyIndexDdl(string name) + => $"CREATE INDEX IF NOT EXISTS {name} ON JsonValue(FullTypeName, CAST(JSON_EXTRACT(Data, '$.Seq') as NUMERIC));"; + + private static List Items() + { + var items = new List(100); + for (int i = 0; i < 100; i++) + { + items.Add(new Item + { + Key = $"item-{i}", + Group = "G" + (i % 10).ToString(CultureInfo.InvariantCulture), + Seq = i, + }); + } + + return items; + } + + // ---------- assertions ---------- + private static async Task AssertLookup(Tycho db) + { + var rows = await db.ReadObjectsAsync( + filter: FilterBuilder.Create().Filter(FilterType.Equals, x => x.Seq, LookupSeq)); + + rows.ShouldHaveSingleItem().Seq.ShouldBe(LookupSeq); + } + + /// The plan for the SQL the library composes for the lookup runs. + private static string ExplainLookup(string dbFile) + { + var sb = new StringBuilder(Queries.SelectDataFromJsonValueWithFullTypeName); + var parameters = new FilterParameters(); + FilterBuilder.Create().Filter(FilterType.Equals, x => x.Seq, LookupSeq).Build(sb, Serializer, parameters); + + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // SQL is produced by the library's own builders. + command.CommandText = "EXPLAIN QUERY PLAN " + sb; +#pragma warning restore CA2100 + + command.Parameters.AddWithValue("$fullTypeName", typeof(Item).FullName); + command.Parameters.AddWithValue("$partition", string.Empty); + for (int i = 0; i < parameters.Count; i++) + { + command.Parameters.AddWithValue( + FilterParameters.ParameterPrefix + i.ToString(CultureInfo.InvariantCulture), + parameters.Values[i] ?? (object)DBNull.Value); + } + + var plan = new StringBuilder(); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + plan.AppendLine(reader.GetString(reader.FieldCount - 1)); + } + + return plan.ToString(); + } + + // ---------- inspection ---------- + private static Dictionary ReadIndexDdl(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL"; + + var result = new Dictionary(StringComparer.Ordinal); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + result[reader.GetString(0)] = reader.GetString(1); + } + + return result; + } + + private static List ReadMetadata(string dbFile) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "SELECT IndexName, FullTypeName, PhysicalName, Definition, ShapeVersion FROM TychoIndex"; + + var rows = new List(); + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + rows.Add(new MetadataRow(reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt64(4))); + } + + return rows; + } + + private static long ReadPragma(string dbFile, string pragma) + => ReadScalar(dbFile, "PRAGMA " + pragma); + + private static long ReadScalar(string dbFile, string sql) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Test-local SQL. + command.CommandText = sql; +#pragma warning restore CA2100 + + return command.ExecuteScalar() is long value ? value : -1; + } + + private static string ReadText(string dbFile, string sql) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Test-local SQL. + command.CommandText = sql; +#pragma warning restore CA2100 + + return command.ExecuteScalar() as string ?? string.Empty; + } + + private static void Execute(string dbFile, string sql) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + +#pragma warning disable CA2100 // Test-local SQL. + command.CommandText = sql; +#pragma warning restore CA2100 + + command.ExecuteNonQuery(); + } + + /// Overwrites the one recorded index's definition, as a tampered file would carry it. + private static void WriteDefinition(string dbFile, string definition) + { + using var conn = OpenInspection(dbFile); + using var command = conn.CreateCommand(); + command.CommandText = "UPDATE TychoIndex SET Definition = $definition"; + command.Parameters.AddWithValue("$definition", definition); + command.ExecuteNonQuery().ShouldBe(1); + } + + private static bool CanOpenForWriting(string dbFile) + { + try + { + using var stream = new FileStream(dbFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); + return true; + } + catch (UnauthorizedAccessException) + { + return false; + } + } + + /// The main file's bytes, once every pooled connection has closed and checkpointed. + private static string FileHash(string dbFile) + { + SqliteConnection.ClearAllPools(); + + using var stream = File.OpenRead(dbFile); + return Convert.ToHexString(SHA256.HashData(stream)); + } + + // ---------- plumbing ---------- + private static (string Path, string DbName) NewDbPath() + { + var dir = Path.Combine(Path.GetTempPath(), "tycho_optimize_tests"); + Directory.CreateDirectory(dir); + return (dir, $"{Guid.NewGuid()}.db"); + } + + private static (string Path, string DbName) Split(string dbFile) + => (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + private static Tycho BuildDb(string path, string dbName) + { +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: true, requireTypeRegistration: false); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: true, requireTypeRegistration: false); +#endif + } + + /// Reopens an existing database without rebuilding it. + private static Tycho BuildDb2(string path, string dbName, bool autoOptimize = true, bool persistConnection = true) + { + SqliteConnection.ClearAllPools(); +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#else + return new Tycho(path, Serializer, dbName, persistConnection: persistConnection, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#endif + } + + /// + /// Opens an inspection connection carrying the same key the database was created with. + /// Tycho holds locking_mode = EXCLUSIVE and pooling keeps a disposed connection's lock + /// alive, so the pool must be cleared after the Tycho instance is disposed and before + /// the file is reopened. + /// + private static SqliteConnection OpenInspection(string dbFile) + { + SqliteConnection.ClearAllPools(); + + var connectionStringBuilder = + new SqliteConnectionStringBuilder + { + ConnectionString = $"Filename={dbFile}", + Cache = SqliteCacheMode.Private, + Mode = SqliteOpenMode.ReadWriteCreate, + }; + +#if ENCRYPTED + connectionStringBuilder.Password = DbPassword; +#endif + + var conn = new SqliteConnection(connectionStringBuilder.ToString()); + conn.Open(); + return conn; + } +} diff --git a/TychoDB.UnitTests/PlannerStatisticsTests.cs b/TychoDB.UnitTests/PlannerStatisticsTests.cs new file mode 100644 index 0000000..874f613 --- /dev/null +++ b/TychoDB.UnitTests/PlannerStatisticsTests.cs @@ -0,0 +1,438 @@ +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() + { + foreach (var autoOptimize in new[] { true, false }) + { + var dbFile = await SeedIndexedStore(); + var (path, dbName) = (Path.GetDirectoryName(dbFile), Path.GetFileName(dbFile)); + + LeaveSampledStatistics(dbFile); + Explain(dbFile, filter: GroupFilter()).ShouldContain(GeneralIndexName, Case.Sensitive); + + using (var db = await BuildDb2(path, dbName, autoOptimize).ConnectAsync()) + { + (await db.ReadObjectsAsync(filter: GroupFilter())).Count().ShouldBe(RowsPerGroup); + } + + ReadStatRows(dbFile).ShouldBeEmpty(); + AssertGroupLookupUsesPartialIndex(dbFile); + } + } + + [TestMethod] + public async Task WithoutStatistics_EqualityUsesThePartialIndex() + { + 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, bool autoOptimize = true) + { + SqliteConnection.ClearAllPools(); +#if ENCRYPTED + return new Tycho(path, Serializer, dbName, DbPassword, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#else + return new Tycho(path, Serializer, dbName, rebuildCache: false, requireTypeRegistration: false, autoOptimize: autoOptimize); +#endif + } + + /// + /// Opens an inspection connection carrying the same key the database was created with. + /// Tycho holds locking_mode = EXCLUSIVE and pooling keeps a disposed connection's lock + /// alive, so the pool must be cleared after the Tycho instance is disposed and before + /// the file is reopened. + /// + private static SqliteConnection OpenInspection(string dbFile) + { + SqliteConnection.ClearAllPools(); + + var connectionStringBuilder = + new SqliteConnectionStringBuilder + { + ConnectionString = $"Filename={dbFile}", + Cache = SqliteCacheMode.Private, + Mode = SqliteOpenMode.ReadWriteCreate, + }; + +#if ENCRYPTED + connectionStringBuilder.Password = DbPassword; +#endif + + var conn = new SqliteConnection(connectionStringBuilder.ToString()); + conn.Open(); + return conn; + } +} diff --git a/TychoDB/Queries.cs b/TychoDB/Queries.cs index 3ac92fe..342452f 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; @@ -46,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, @@ -63,6 +59,9 @@ CREATE TABLE IF NOT EXISTS StreamValue PRIMARY KEY (Key, Partition) ); + -- ShapeVersion is the generated index shape the row was built in, or 0 for a + -- definition recorded under autoOptimize:false and not built yet (see + -- Tycho.PendingIndexShapeVersion). CREATE TABLE IF NOT EXISTS TychoIndex ( IndexName TEXT NOT NULL, @@ -74,6 +73,21 @@ PRIMARY KEY (IndexName, FullTypeName) ); """; + // Indexes earlier versions created that duplicate either the primary-key autoindex + // or a prefix of idx_jsonvalue_fulltypename_partition. Each one costs a full b-tree + // of write maintenance on every insert, update and delete while serving no query + // the remaining indexes cannot. Idempotent, and a no-op once they are gone; but + // freeing their pages on an upgraded store takes time proportional to their size, + // so the connect script includes this only when autoOptimize is on (see + // Tycho.Optimize). + public const string DropLegacyIndexes = + """ + DROP INDEX IF EXISTS idx_jsonvalue_fulltypename; + DROP INDEX IF EXISTS idx_jsonvalue_key_fulltypename; + DROP INDEX IF EXISTS idx_jsonvalue_key_fulltypename_partition; + DROP INDEX IF EXISTS idx_streamvalue_key_partition; + """; + // Profile defaults. cache_size is in KiB (negative = KiB, not pages); // mmap_size is in bytes; wal_autocheckpoint is in pages. private const int MobileCacheSizeKb = 8_000; // ~8 MB page cache @@ -91,12 +105,16 @@ PRIMARY KEY (IndexName, FullTypeName) /// /// Builds the full per-connection setup script (PRAGMAs + schema DDL) for the - /// given performance profile, honoring optional cache-size / mmap overrides. + /// given performance profile, honoring optional cache-size / mmap overrides, and + /// shedding the indexes earlier versions created unless told not to. 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 dropLegacyIndexes = true, + bool newDatabase = true) { bool desktop = profile == TychoPerformanceProfile.Desktop; @@ -105,9 +123,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 + DropLegacyIndexes.Length + 160); var ic = System.Globalization.CultureInfo.InvariantCulture; + if (newDatabase) + { + sb.Append(CreationPragma).Append('\n'); + } + sb.Append(SharedPragmas).Append('\n') .Append("PRAGMA cache_size = -").Append(cacheSizeKb.ToString(ic)).Append(";\n") .Append("PRAGMA mmap_size = ").Append(mmapSizeBytes.ToString(ic)).Append(";\n") @@ -115,6 +138,11 @@ public static string BuildConnectionScript( .Append("PRAGMA journal_size_limit = ").Append(journalSizeLimit.ToString(ic)).Append(";\n\n") .Append(SchemaDdl); + if (dropLegacyIndexes) + { + sb.Append('\n').Append(DropLegacyIndexes); + } + return sb.ToString(); } @@ -561,10 +589,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 +618,189 @@ FROM TychoIndex public const string SelectPhysicalIndexExists = "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + public const string SelectIndexRecordedByAnother = + """ + SELECT 1 + FROM TychoIndex + WHERE PhysicalName = $physicalName + AND NOT (IndexName = $indexName AND FullTypeName = $fullTypeName); + """; + + public const string SelectIndexSql = + "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = $physicalName;"; + + public const string SelectIndexNames = + "SELECT name FROM sqlite_master WHERE type = 'index';"; + + /// + /// The text sqlite_master keeps for an index this class's DDL created: SQLite stores + /// "CREATE INDEX " and then the statement from the index name on, verbatim, so the + /// IF NOT EXISTS and the closing semicolon are not part of it. + /// + public static string StoredIndexSql(string createIndexStatement) + => string.Concat("CREATE INDEX ".AsSpan(), createIndexStatement.AsSpan(CreateIndexPrefix.Length).TrimEnd(';')); + + /// + /// Whether is, byte for byte, a statement + /// + /// builds for the index named. The text is taken apart into the paths and the type it + /// indexes, each path is checked as a declaration's is, and the statement is built + /// again from them and compared. The value is read back out of the TychoIndex table + /// and executed as it stands, so it is re-checked rather than trusted: anything added + /// to it — a second statement, an expression this class never emits — does not survive + /// the round trip. + /// + public static bool IsIndexDefinitionFor(string definition, string physicalName) + => TryParseIndexDefinition(definition, physicalName, out var propertyPaths, out var fullTypeName) + && string.Equals(definition, CreateIndexForJsonValue(physicalName, propertyPaths, fullTypeName), StringComparison.Ordinal); + + private static bool TryParseIndexDefinition( + string definition, + string physicalName, + out (string PropertyPathString, bool IsNumeric)[] propertyPaths, + out string? fullTypeName) + { + propertyPaths = Array.Empty<(string PropertyPathString, bool IsNumeric)>(); + fullTypeName = null; + + var rest = definition.AsSpan(); + + if (!Consume(ref rest, CreateIndexPrefix) || !Consume(ref rest, physicalName)) + { + return false; + } + + bool partial = Consume(ref rest, PartialIndexOnJsonValue); + + if (!partial && !(Consume(ref rest, MultiIndexOnJsonValue) && Consume(ref rest, PartitionColumnSegment))) + { + return false; + } + + var paths = new List<(string PropertyPathString, bool IsNumeric)>(); + + while (true) + { + bool numeric = Consume(ref rest, MultiIndexCastPrefix); + + if (!numeric && !Consume(ref rest, MultiIndexJsonExtractPrefix)) + { + break; + } + + int pathEnd = rest.IndexOf('\''); + + if (pathEnd < 0) + { + return false; + } + + string path = rest[..pathEnd].ToString(); + rest = rest[pathEnd..]; + + if (!QueryPropertyPath.IsValidPath(path) + || !Consume(ref rest, numeric ? MultiIndexCastSuffix : MultiIndexJsonExtractSuffix)) + { + return false; + } + + paths.Add((path, numeric)); + } + + if (paths.Count == 0) + { + return false; + } + + propertyPaths = paths.ToArray(); + + if (!partial) + { + return rest.SequenceEqual(MultiIndexClose.AsSpan()); + } + + if (!Consume(ref rest, ")") + || !Consume(ref rest, PartialIndexWherePrefix) + || !rest.EndsWith(PartialIndexWhereSuffix.AsSpan(), StringComparison.Ordinal)) + { + return false; + } + + fullTypeName = rest[..^PartialIndexWhereSuffix.Length].ToString().Replace("''", "'", StringComparison.Ordinal); + return true; + } + + private static bool Consume(ref ReadOnlySpan text, string token) + { + if (!text.StartsWith(token.AsSpan(), StringComparison.Ordinal)) + { + return false; + } + + text = text[token.Length..]; + return true; + } + + // Planner statistics. TychoDB gathers none — SQLite's default heuristics choose the + // right index for every query it emits, and sampled statistics made the planner read + // every row of a type on each indexed lookup (5.3.0, 5.3.1) — and deletes what an + // earlier release or an external ANALYZE left, reloading so the open connection + // forgets them. Only the rows go: dropping the table is pointless, since ANALYZE + // sqlite_master recreates it, and a store with no rows is not written to. + public const string SelectStatisticsTableExists = + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_stat1';"; + + public const string SelectStatisticsRowExists = + "SELECT 1 FROM sqlite_stat1 LIMIT 1;"; + + public const string DeleteStatistics = + """ + DELETE FROM sqlite_stat1; + ANALYZE sqlite_master; + """; + + 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 = "-compact"; + + // SQLCipher turns secure_delete on, and with it every page a DROP INDEX frees is + // zeroed through the WAL first, so the drops need free space equal to the index. + // Pointless when the whole file is about to be rewritten, so Optimize turns it off + // for its drops when a compaction follows and restores the mode it found. + public const string SecureDelete = "PRAGMA secure_delete;"; + + public const string SecureDeleteOff = "PRAGMA secure_delete = OFF;"; + + public static string RestoreSecureDelete(long mode) + => mode switch + { + 1 => "PRAGMA secure_delete = ON;", + 2 => "PRAGMA secure_delete = FAST;", + _ => SecureDeleteOff, + }; + // Cache common LIMIT values using FrozenDictionary for O(1) lookup private static readonly FrozenDictionary CachedLimits = new Dictionary { diff --git a/TychoDB/QueryPropertyPath.cs b/TychoDB/QueryPropertyPath.cs index 048c247..a1d27d1 100644 --- a/TychoDB/QueryPropertyPath.cs +++ b/TychoDB/QueryPropertyPath.cs @@ -249,7 +249,7 @@ public static void ValidatePath(string path, string paramName) foreach (var c in path) { - if (!(char.IsLetterOrDigit(c) || c is '$' or '.' or '_' or '[' or ']')) + if (!IsPathChar(c)) { throw new ArgumentException( $"Property path contains an invalid character '{c}'. Only letters, digits, '_', '.', '$', '[' and ']' are permitted.", @@ -258,6 +258,31 @@ public static void ValidatePath(string path, string paramName) } } + /// + /// Whether would pass : the check for + /// a path read back out of the database rather than supplied by a caller. + /// + public static bool IsValidPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + foreach (var c in path) + { + if (!IsPathChar(c)) + { + return false; + } + } + + return true; + } + + private static bool IsPathChar(char c) + => char.IsLetterOrDigit(c) || c is '$' or '.' or '_' or '[' or ']'; + /// /// Validates a caller-supplied SQL identifier (e.g. an index name). Identifiers /// are concatenated into DDL and cannot be parameterized, so they are limited diff --git a/TychoDB/Tycho.cs b/TychoDB/Tycho.cs index 82fcfa7..bc5d315 100644 --- a/TychoDB/Tycho.cs +++ b/TychoDB/Tycho.cs @@ -36,17 +36,33 @@ private const string /// private const int IndexShapeVersion = 2; + /// + /// The ShapeVersion recorded for an index whose build was deferred: the definition is + /// the one will build, and the physical index it names is not + /// in the schema yet — whatever index the previous release built for the same + /// declaration still is, and serves queries meanwhile. + /// + private const int PendingIndexShapeVersion = 0; + + // SQLITE_FULL: the result code SQLite reports when the volume has no room for a + // write, which is the one failure the compaction skips rather than raises. + private const int SqliteFull = 13; + // Parameter cache - reuse parameter objects to reduce allocations private readonly ConcurrentDictionary _parameterCache = new(); 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; + private readonly bool _autoOptimize; // One rewrite per type, so its divergence verdict is probed once and reused. private readonly ConcurrentDictionary _keyColumnRewrites = new(); @@ -104,6 +120,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 the indexes in place, and CreateIndex records the wanted + /// definition as pending while queries keep using the index the previous release + /// built — and call or from a + /// background thread at a convenient time. Default is true. + /// public Tycho( string dbPath, IJsonSerializer jsonSerializer, @@ -116,7 +142,8 @@ public Tycho( int commandTimeout = 30, TychoPerformanceProfile performanceProfile = TychoPerformanceProfile.Mobile, int? cacheSizeKb = null, - long? mmapSizeBytes = null) + long? mmapSizeBytes = null, + bool autoOptimize = true) { SQLitePCL.Batteries_V2.Init(); @@ -153,7 +180,10 @@ public Tycho( _dbConnectionString = connectionStringBuilder.ToString(); _persistConnection = persistConnection; _requireTypeRegistration = requireTypeRegistration; - _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes); + _autoOptimize = autoOptimize; + _databasePath = databasePath; + _connectionScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: false); + _creationScript = Queries.BuildConnectionScript(performanceProfile, cacheSizeKb, mmapSizeBytes, autoOptimize, newDatabase: true); } /// @@ -270,7 +300,6 @@ public void Disconnect() { if (_connection is not null) { - RunOptimize(_connection); _connection.Close(); _connection.Dispose(); _connection = null; @@ -289,40 +318,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); @@ -2228,52 +2229,89 @@ private static void ExecuteNonQuery(SqliteConnection conn, string commandText) } /// - /// Creates an index if an identical one is not already recorded, migrating away - /// from any previous shape or name for the same logical index. + /// Brings the schema in line with one index declaration. + /// + /// Mobile apps declare their indexes on every launch, so the already-current case + /// must be cheap: one metadata lookup and two sqlite_master probes, no DDL. The probe + /// reads the physical index's stored DDL rather than its mere presence, so a + /// same-named index of another shape — the one 4.x built under the name the string + /// overload still uses, which CREATE INDEX IF NOT EXISTS would keep without a + /// word — counts as stale, and a stale index is rebuilt. + /// /// - /// Mobile apps typically call CreateIndex on every launch, so the already-current - /// case must be cheap: it costs one metadata lookup and one sqlite_master probe, - /// with no DDL and no ANALYZE. + /// With the rebuild happens here. Without it, when + /// an index the previous release built for the same declaration is still in the + /// schema, the wanted definition is recorded as pending and that index keeps serving + /// queries until replaces it; a declaration nothing in the + /// schema serves is built here either way, because no index is the slower outcome. + /// + /// + /// The index under the legacy name goes once the current one serves — unless another + /// TychoIndex row records that name as its own index, as the string overload's does + /// when an app declares one name through both overloads; that index is left alone, + /// as and leave it. /// /// - private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition) + private static bool ExecuteCreateIndex(SqliteConnection conn, IndexDefinition definition, bool migrateInline) { using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); try { - if (IsIndexCurrent(conn, definition)) + var recorded = ReadRecordedIndex(conn, definition); + string? physicalSql = ReadIndexSql(conn, definition.PhysicalName); + bool hasLegacyName = !string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal); + bool legacyPresent = hasLegacyName + ? IndexExists(conn, definition.LegacyPhysicalName) + : physicalSql is not null; + bool legacyOrphan = hasLegacyName && legacyPresent + && !IsRecordedByAnotherIndex(conn, definition.LegacyPhysicalName, definition.IndexName, definition.MetadataTypeName); + + if (string.Equals(physicalSql, Queries.StoredIndexSql(definition.CommandText), StringComparison.Ordinal)) { + if (!IsRecordedAs(recorded, definition, IndexShapeVersion)) + { + UpsertIndexMetadata(conn, definition, IndexShapeVersion); + } + + if (legacyOrphan && migrateInline) + { + ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + } + transaction.Commit(); return true; } - // Drop the previously recorded physical index (shape or definition - // changed) and any pre-metadata index that used the legacy name, so an - // upgraded database does not keep maintaining a stale b-tree forever. - foreach (var stalePhysicalName in ReadRecordedPhysicalNames(conn, definition)) + if (legacyPresent && !migrateInline) { - ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stalePhysicalName))); + if (!IsRecordedAs(recorded, definition, PendingIndexShapeVersion)) + { + UpsertIndexMetadata(conn, definition, PendingIndexShapeVersion); + } + + transaction.Commit(); + return true; } - if (!string.Equals(definition.LegacyPhysicalName, definition.PhysicalName, StringComparison.Ordinal)) + if (recorded is { } stale && !string.Equals(stale.PhysicalName, definition.PhysicalName, StringComparison.Ordinal)) { - ExecuteNonQuery(conn, Queries.DropIndex(definition.LegacyPhysicalName)); + ExecuteNonQuery(conn, Queries.DropIndex(ValidateStoredIndexName(stale.PhysicalName))); } - ExecuteNonQuery(conn, definition.CommandText); + if (physicalSql is not null) + { + ExecuteNonQuery(conn, Queries.DropIndex(definition.PhysicalName)); + } - using (var upsert = conn.CreateCommand()) + if (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, IndexShapeVersion); + transaction.Commit(); } catch (Exception ex) @@ -2282,72 +2320,101 @@ 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; } - /// - /// True when the recorded definition matches what would be created now and the - /// physical index is still present in the schema. - /// - private static bool IsIndexCurrent(SqliteConnection conn, IndexDefinition definition) + /// One row of the TychoIndex metadata table, as stored. + private readonly record struct IndexMetadataRow( + string IndexName, + string FullTypeName, + string PhysicalName, + string Definition, + long ShapeVersion); + + private static IndexMetadataRow? ReadRecordedIndex(SqliteConnection conn, IndexDefinition definition) { using var lookup = conn.CreateCommand(); lookup.CommandText = Queries.SelectIndexMetadata; lookup.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = definition.IndexName }); lookup.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = definition.MetadataTypeName }); - string? recordedDefinition = null; - long recordedVersion = -1; + using var reader = lookup.ExecuteReader(); - using (var reader = lookup.ExecuteReader()) - { - if (reader.Read()) - { - recordedDefinition = reader.GetString(1); - recordedVersion = reader.GetInt64(2); - } - } + return reader.Read() + ? new IndexMetadataRow(definition.IndexName, definition.MetadataTypeName, 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 IsRecordedAs(IndexMetadataRow? recorded, IndexDefinition definition, int shapeVersion) + => recorded is { } row + && row.ShapeVersion == shapeVersion + && string.Equals(row.Definition, definition.CommandText, StringComparison.Ordinal); + + /// The stored DDL of the index named, or null when the schema has no such index. + private static string? ReadIndexSql(SqliteConnection conn, string physicalName) + { + using var lookup = conn.CreateCommand(); + lookup.CommandText = Queries.SelectIndexSql; + lookup.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); + return lookup.ExecuteScalar() as string; + } + private static bool IndexExists(SqliteConnection conn, string physicalName) + { using var exists = conn.CreateCommand(); exists.CommandText = Queries.SelectPhysicalIndexExists; - exists.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = definition.PhysicalName }); + exists.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); return exists.ExecuteScalar() is not null; } - private static List ReadRecordedPhysicalNames(SqliteConnection conn, IndexDefinition definition) + /// + /// 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, int shapeVersion) + => UpsertIndexMetadata(conn, definition.IndexName, definition.MetadataTypeName, definition.PhysicalName, definition.CommandText, shapeVersion); - return names; + private static void UpsertIndexMetadata( + SqliteConnection conn, + string indexName, + string typeName, + string physicalName, + string definitionText, + int shapeVersion) + { + using var upsert = conn.CreateCommand(); + upsert.CommandText = Queries.UpsertIndexMetadata; + upsert.Parameters.Add(new SqliteParameter("$indexName", SqliteType.Text) { Value = indexName }); + upsert.Parameters.Add(new SqliteParameter("$fullTypeName", SqliteType.Text) { Value = typeName }); + upsert.Parameters.Add(new SqliteParameter("$physicalName", SqliteType.Text) { Value = physicalName }); + upsert.Parameters.Add(new SqliteParameter("$definition", SqliteType.Text) { Value = definitionText }); + upsert.Parameters.Add(new SqliteParameter("$shapeVersion", SqliteType.Integer) { Value = shapeVersion }); + upsert.ExecuteNonQuery(); + } + + /// + /// 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( @@ -2368,8 +2435,8 @@ private Tycho CreateIndexCore( _connection .WithConnectionBlock( _connectionGate, - definition, - static (conn, state) => ExecuteCreateIndex(conn, state), + (definition, migrateInline: _autoOptimize), + static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.migrateInline), _persistConnection); return this; @@ -2394,8 +2461,8 @@ private ValueTask CreateIndexCoreAsync( return _connection .WithConnectionBlockAsync( _connectionGate, - definition, - static (conn, state) => ExecuteCreateIndex(conn, state), + (definition, migrateInline: _autoOptimize), + static (conn, state) => ExecuteCreateIndex(conn, state.definition, state.migrateInline), _persistConnection, cancellationToken); } @@ -2585,6 +2652,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; @@ -2604,8 +2677,10 @@ private static bool ExecuteDropIndex(SqliteConnection conn, string indexName, st } /// - /// Lists the indexes Tycho has created, as recorded in its metadata table. - /// Indexes created directly against the database outside Tycho are not listed. + /// Lists the indexes Tycho has created, as recorded in its metadata table. An index + /// declared under autoOptimize: false whose build has + /// not done yet is listed with the definition it will get. Indexes created directly + /// against the database outside Tycho are not listed. /// /// The recorded indexes, ordered by type then index name. public IReadOnlyList ListIndexes() @@ -2618,19 +2693,12 @@ public IReadOnlyList ListIndexes() null, static (conn, _) => { - var results = new List(); - - using var command = conn.CreateCommand(); - command.CommandText = Queries.SelectAllIndexMetadata; + var rows = ReadIndexMetadata(conn); + var results = new List(rows.Count); - using var reader = command.ExecuteReader(); - while (reader.Read()) + foreach (var row in rows) { - results.Add(new TychoIndexInfo( - reader.GetString(0), - reader.GetString(1), - reader.GetString(2), - reader.GetString(3))); + results.Add(new TychoIndexInfo(row.IndexName, row.FullTypeName, row.PhysicalName, row.Definition)); } return results; @@ -2638,6 +2706,417 @@ public IReadOnlyList ListIndexes() _persistConnection); } + private static List ReadIndexMetadata(SqliteConnection conn) + { + var rows = new List(); + + using var command = conn.CreateCommand(); + command.CommandText = Queries.SelectAllIndexMetadata; + + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + rows.Add(new IndexMetadataRow( + reader.GetString(0), + reader.GetString(1), + reader.GetString(2), + reader.GetString(3), + reader.GetInt64(4))); + } + + return rows; + } + + private static HashSet ReadIndexNames(SqliteConnection conn) + { + var names = new HashSet(StringComparer.Ordinal); + + using var command = conn.CreateCommand(); + command.CommandText = Queries.SelectIndexNames; + + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + names.Add(reader.GetString(0)); + } + + return names; + } + + /// + /// Does the one-time work an upgraded store needs, in one hold of the connection: + /// drops the four redundant indexes 4.x created; builds every index + /// CreateIndex recorded as pending under autoOptimize: false and drops + /// the index the previous release built for it; drops the per-type indexes a 4.x + /// rollback recreated next to their replacements; deletes planner statistics an + /// external ANALYZE left; and returns the pages all of that freed to the file + /// system — by rewriting the store into a compacted copy and swapping it in when the + /// store was created without incremental auto-vacuum (every 4.x store), which also + /// converts it (see ), or by an in-place + /// incremental_vacuum when at least a tenth of the file is free. Idempotent: + /// with nothing pending it reads the schema and writes nothing, so calling it on + /// every launch is fine. + /// + /// Holds the database's single connection for the duration, so every other + /// operation on this instance waits: on a 1.8M-row, 3 GB store upgraded from 4.x the + /// drops and the rebuilds took about 9 s each, and the compaction needs free disk + /// space for the compacted copy — the live pages, about a third of that file — and is + /// skipped, to be retried by the next call, when the space is not there. The work + /// runs on the calling thread — Microsoft.Data.Sqlite executes synchronously, so + /// does not move it off the caller by itself — and must + /// not be called from a UI thread. + /// + /// + public void Optimize() + { + ArgumentNullException.ThrowIfNull(_connection); + + _connectionGate.Wait(); + + try + { + OptimizeStore(); + } + finally + { + _connectionGate.Release(); + } + } + + /// + /// Asynchronously does what does, with the same cost. It + /// holds the database's single connection for the duration and runs on the calling + /// thread — Microsoft.Data.Sqlite executes synchronously, so this method does not + /// move the work off the caller by itself — and must not be called from a UI thread. + /// + /// A token to cancel the asynchronous operation. + /// A ValueTask containing true when the store was optimized. + public async ValueTask OptimizeAsync(CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(_connection); + + await _connectionGate.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + OptimizeStore(); + } + finally + { + _connectionGate.Release(); + } + + return true; + } + + /// + /// Runs under the gate. The compaction replaces the connection, so nothing here + /// keeps the object the gate was entered with past that point. + /// + private void OptimizeStore() + { + var conn = GatedConnection(); + + try + { + bool compact = ReadPragma(conn, Queries.AutoVacuumMode) == 0; + long secureDelete = compact ? ReadPragma(conn, Queries.SecureDelete) : 0; + + try + { + if (secureDelete != 0) + { + ExecuteNonQuery(conn, Queries.SecureDeleteOff); + } + + try + { + ExecuteNonQuery(conn, Queries.DropLegacyIndexes); + RebuildPendingIndexes(conn); + RemoveLeftoverStatistics(conn); + } + finally + { + if (secureDelete != 0) + { + ExecuteNonQuery(conn, Queries.RestoreSecureDelete(secureDelete)); + } + } + + if (!compact) + { + ReclaimFreePages(conn); + } + } + catch (Exception ex) when (ex is not TychoException) + { + throw new TychoException("Failed to optimize database", ex); + } + + if (compact) + { + CompactStore(); + } + } + finally + { + ReleaseGatedConnection(); + } + } + + private SqliteConnection GatedConnection() + { + var conn = _connection ?? throw new TychoException("Please call 'Connect' before performing an operation"); + + if (!_persistConnection) + { + conn.Open(); + } + + return conn; + } + + private void ReleaseGatedConnection() + { + if (!_persistConnection) + { + _connection?.Close(); + } + } + + /// + /// Rewrites a store that has no incremental auto-vacuum (every 4.x store) into a + /// compacted copy next to the file, with VACUUM INTO, and swaps the copy in: + /// the connection closes, which checkpoints the WAL into the file; the -wal and + /// -shm files are deleted; the copy is renamed over the database; and the + /// connection reopens on it. Only the live pages are written, once, into the + /// database's own directory — no temp copy, nothing back through the WAL — so the free + /// space needed is the compacted size. The WAL goes before the rename because SQLite + /// checks a WAL only against its own header, so one left next to the new file would be + /// replayed into it. The connection holds the file exclusively, so a WAL still on disk + /// with frames after the close means the close could not checkpoint it and the file + /// may lack commits only the WAL holds; the copy is discarded instead. The database is + /// untouched until the rename, which is atomic: an interruption leaves the old file + /// working and at most a leftover copy, which the next call removes. Skipped, to be + /// retried by the next call, when the volume lacks the space, SQLite reports it full, + /// or such a WAL remains. Runs under the gate. + /// + private void CompactStore() + { + var connection = _connection!; + string compactedPath = _databasePath + Queries.CompactedFileSuffix; + + long liveBytes = + (ReadPragma(connection, Queries.PageCount) - ReadPragma(connection, Queries.FreelistCount)) + * ReadPragma(connection, Queries.PageSize); + + if (!HasFreeSpaceFor(liveBytes)) + { + return; + } + + File.Delete(compactedPath); + + try + { + ExecuteNonQuery(connection, Queries.SetIncrementalAutoVacuum); + + using var vacuum = connection.CreateCommand(); + vacuum.CommandText = Queries.VacuumInto; + vacuum.Parameters.Add(new SqliteParameter("$path", SqliteType.Text) { Value = compactedPath }); + vacuum.ExecuteNonQuery(); + } + catch (SqliteException ex) when (ex.SqliteErrorCode == SqliteFull) + { + File.Delete(compactedPath); + return; + } + catch (Exception ex) + { + File.Delete(compactedPath); + throw new TychoException("Failed to compact database", ex); + } + + connection.Dispose(); + SqliteConnection.ClearPool(connection); + _connection = null; + + string walPath = _databasePath + "-wal"; + + if (new FileInfo(walPath) is { Exists: true, Length: > 0 }) + { + File.Delete(compactedPath); + _connection = OpenConnection(_connectionScript); + return; + } + + try + { + File.Delete(walPath); + File.Delete(_databasePath + "-shm"); + File.Move(compactedPath, _databasePath, overwrite: true); + } + catch (Exception ex) + { + File.Delete(compactedPath); + _connection = OpenConnection(_connectionScript); + throw new TychoException("Failed to compact database", ex); + } + + _connection = OpenConnection(_connectionScript); + } + + /// + /// Whether the volume holding the database has room for and + /// an eighth more. True when the volume cannot be asked: the compaction then relies + /// on SQLite reporting a full disk, which leaves the database untouched. + /// + private bool HasFreeSpaceFor(long bytes) + { + try + { + string fullPath = Path.GetFullPath(_databasePath); + string directory = Path.GetDirectoryName(fullPath) ?? fullPath; + + return new DriveInfo(directory).AvailableFreeSpace >= bytes + (bytes / 8); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return true; + } + } + + /// + /// Builds each index recorded as pending in a transaction of its own, dropping the + /// index the previous release built for it, so an interruption leaves that index + /// either as it was or complete; and drops the legacy-named index a 4.x rollback + /// recreated next to a current one. A legacy name another row records as its own + /// index is left alone. + /// + private static void RebuildPendingIndexes(SqliteConnection conn) + { + var rows = ReadIndexMetadata(conn); + + if (rows.Count == 0) + { + return; + } + + var indexNames = ReadIndexNames(conn); + var recordedNames = new HashSet(StringComparer.Ordinal); + + foreach (var row in rows) + { + recordedNames.Add(row.PhysicalName); + } + + foreach (var row in rows) + { + string physicalName = ValidateStoredIndexName(row.PhysicalName); + string? legacyName = LegacyPhysicalNameOf(physicalName, row.FullTypeName); + string? orphanName = legacyName is not null && indexNames.Contains(legacyName) && !recordedNames.Contains(legacyName) + ? legacyName + : null; + + if (row.ShapeVersion == IndexShapeVersion) + { + if (orphanName is not null) + { + ExecuteNonQuery(conn, Queries.DropIndex(orphanName)); + } + + continue; + } + + if (!Queries.IsIndexDefinitionFor(row.Definition, physicalName)) + { + throw new TychoException($"Index metadata for {row.IndexName} does not define {physicalName}"); + } + + using var transaction = conn.BeginTransaction(IsolationLevel.Serializable); + + try + { + if (orphanName is not null) + { + ExecuteNonQuery(conn, Queries.DropIndex(orphanName)); + } + + if (indexNames.Contains(physicalName)) + { + ExecuteNonQuery(conn, Queries.DropIndex(physicalName)); + } + + ExecuteNonQuery(conn, row.Definition); + UpsertIndexMetadata(conn, row.IndexName, row.FullTypeName, physicalName, row.Definition, IndexShapeVersion); + + transaction.Commit(); + } + catch (Exception ex) + { + transaction.Rollback(); + throw new TychoException($"Failed to Create Index: {physicalName}", ex); + } + } + } + + /// + /// Deletes planner statistics an earlier release or an external ANALYZE left + /// in the file and reloads them on this connection. TychoDB gathers none: SQLite's + /// default heuristics choose the right index for every query it emits, and sampled + /// statistics made the planner read every row of a type on each indexed lookup + /// (5.3.0, 5.3.1). Writes nothing when there is nothing to delete, so a current + /// store's connect is read-only, and never drops the table: ANALYZE + /// sqlite_master would recreate it. + /// + private static void RemoveLeftoverStatistics(SqliteConnection conn) + { + if (ExecuteScalar(conn, Queries.SelectStatisticsTableExists) is null + || ExecuteScalar(conn, Queries.SelectStatisticsRowExists) is null) + { + return; + } + + ExecuteNonQuery(conn, Queries.DeleteStatistics); + } + + /// + /// Returns freed pages to the file system in place, on a store with incremental + /// auto-vacuum, when at least a tenth of the file is free, so a store with a little + /// churn is left alone. A store created without it — every 4.x store: its connect + /// script set the pragma after journal_mode = WAL, which fixed the mode at + /// NONE — is converted by instead, after which later + /// calls take this path. + /// + private static void ReclaimFreePages(SqliteConnection conn) + { + if (ReadPragma(conn, Queries.AutoVacuumMode) != 2) + { + return; + } + + long freePages = ReadPragma(conn, Queries.FreelistCount); + + if (freePages > 0 && freePages * 10 >= ReadPragma(conn, Queries.PageCount)) + { + ExecuteNonQuery(conn, Queries.IncrementalVacuum); + } + } + + private static object? ExecuteScalar(SqliteConnection conn, string commandText) + { + using var command = conn.CreateCommand(); + +#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. /// @@ -2647,71 +3126,61 @@ public IReadOnlyList ListIndexes() /// auto-vacuum mode this runs a cheap in-place incremental_vacuum. On a /// legacy database that was created without incremental auto-vacuum (e.g. by an /// older version, or before the auto_vacuum ordering fix), incremental_vacuum - /// is a no-op, so this instead runs a one-time full VACUUM that both reclaims - /// the space and converts the database to incremental auto-vacuum for the future. + /// is a no-op, so this instead rewrites the database into a compacted copy and swaps + /// it in, which both reclaims the space and converts the database to incremental + /// auto-vacuum for the future; that needs free disk space for the compacted copy and + /// is skipped when the space is not there (see ). /// public void Cleanup(bool shrinkMemory = true, bool vacuum = false) { ArgumentNullException.ThrowIfNull(_connection); - _connection - .WithConnectionBlock( - _connectionGate, - (shrinkMemory, vacuum), - static (conn, state) => - { - try - { - if (state.shrinkMemory) - { - using var shrinkCommand = conn.CreateCommand(); - shrinkCommand.CommandText = "PRAGMA shrink_memory;"; - shrinkCommand.ExecuteNonQuery(); - } + _connectionGate.Wait(); - if (!state.vacuum) - { - return; - } + try + { + var conn = GatedConnection(); - // incremental_vacuum only reclaims space when the database is in - // INCREMENTAL (2) auto-vacuum mode. - long autoVacuumMode; - using (var modeCommand = conn.CreateCommand()) - { - modeCommand.CommandText = "PRAGMA auto_vacuum;"; - autoVacuumMode = modeCommand.ExecuteScalar() is long mode ? mode : 0L; - } + try + { + bool compact = false; - using var vacuumCommand = conn.CreateCommand(); + try + { + if (shrinkMemory) + { + ExecuteNonQuery(conn, Queries.ShrinkMemory); + } - 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 + if (vacuum) + { + compact = ReadPragma(conn, Queries.AutoVacuumMode) == 0; + + if (!compact) { - // 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);"; + ExecuteNonQuery(conn, Queries.IncrementalVacuum); } - - vacuumCommand.ExecuteNonQuery(); - } - catch (Exception ex) - { - throw new TychoException("Failed to clean up database", ex); } - }, - _persistConnection); + } + catch (Exception ex) + { + throw new TychoException("Failed to clean up database", ex); + } + + if (compact) + { + CompactStore(); + } + } + finally + { + ReleaseGatedConnection(); + } + } + finally + { + _connectionGate.Release(); + } } /// @@ -2898,11 +3367,6 @@ protected virtual void Dispose(bool disposing) if (disposing) { - if (_connection is not null) - { - RunOptimize(_connection); - } - _connectionGate?.Dispose(); _connection?.Close(); _connection?.Dispose(); @@ -2961,34 +3425,23 @@ private static string ToSafeIdentifier(string derivedTypeName) private SqliteConnection BuildConnection() { - var connection = new SqliteConnection(_dbConnectionString); - - connection - .WithConnectionBlock( - _connectionGate, - _connectionScript, - static (conn, script) => - { - conn.Open(); - - // Verified once per process (see EnsureJsonSupport). - EnsureJsonSupport(conn); + _connectionGate.Wait(); - using var command = conn.CreateCommand(); - - // Profile PRAGMAs + idempotent schema/index creation. Composed from - // library constants and numeric profile values only (no user input). -#pragma warning disable CA2100 - command.CommandText = script; -#pragma warning restore CA2100 - - command.ExecuteNonQuery(); + try + { + var connection = OpenConnection(ConnectionScript()); - RunOptimize(conn); - }, - _persistConnection); + if (!_persistConnection) + { + connection.Close(); + } - return connection; + return connection; + } + finally + { + _connectionGate.Release(); + } } private async ValueTask BuildConnectionAsync(CancellationToken cancellationToken = default) @@ -2997,34 +3450,73 @@ private async ValueTask BuildConnectionAsync(CancellationToken try { - var connection = new SqliteConnection(_dbConnectionString); + return OpenConnection(ConnectionScript()); + } + finally + { + _connectionGate.Release(); + } + } + /// + /// Opens a connection on the file and runs on it. Called + /// under the gate: by Connect, and by to reopen the store + /// it swapped in. A connection whose setup fails is disposed before the failure + /// propagates, so it does not keep the file's lock until the finalizer runs. The + /// statistics delete is best-effort here, as the PRAGMA optimize it replaced + /// was: a store on a read-only file or a full volume connects, and the planner stays + /// misled until a connect that can write; reports the failure. + /// + private SqliteConnection OpenConnection(string script) + { + var connection = new SqliteConnection(_dbConnectionString); + + try + { connection.Open(); // JSON support depends only on the process-wide native SQLite build, so // it is verified once and cached rather than re-queried on every connect. EnsureJsonSupport(connection); - await using var command = connection.CreateCommand(); + using var command = connection.CreateCommand(); // Profile PRAGMAs + idempotent schema/index creation. Composed from // library constants and numeric profile values only (no user input). #pragma warning disable CA2100 - command.CommandText = _connectionScript; + command.CommandText = script; #pragma warning restore CA2100 command.ExecuteNonQuery(); - RunOptimize(connection); + try + { + RemoveLeftoverStatistics(connection); + } + catch (SqliteException) + { + } return connection; } - finally + catch { - _connectionGate.Release(); + connection.Dispose(); + throw; } } + /// + /// 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; diff --git a/docs/indexing-analysis.md b/docs/indexing-analysis.md index deebbb7..5505baa 100644 --- a/docs/indexing-analysis.md +++ b/docs/indexing-analysis.md @@ -124,6 +124,11 @@ win; the query-plan sweep in that bucket must confirm no query regresses to a ta ## 5. Statistics +> **5.4.0:** the bounded `ANALYZE` and `PRAGMA optimize` this section led to sampled the +> indexes and misled the planner; TychoDB gathers no statistics now. See +> `docs/planner-statistics-sampling.md` for the regression and the design that replaced +> them. + `sqlite_stat1` does not exist even after a full connect→index-create→dispose cycle — `Disconnect`'s `PRAGMA optimize` produced no statistics table in the diagnose run. All plans above are chosen by default heuristics. Bucket 3 adds a bounded `ANALYZE` after diff --git a/docs/planner-statistics-sampling.md b/docs/planner-statistics-sampling.md new file mode 100644 index 0000000..078df5f --- /dev/null +++ b/docs/planner-statistics-sampling.md @@ -0,0 +1,241 @@ +# 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. + +## 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` (pending, 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`; 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 — the + instance keeps serving on the swapped-in file, a leftover copy is replaced, it works + without a persistent connection, and `Cleanup(vacuum: true)` takes the same path. + +Bound parameters are fine in the library: SQLite re-plans when a bound value touches a +partial-index `WHERE`, so `EXPLAIN QUERY PLAN` on an unbound statement shows the generic +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 most of a 10–30 s stall +MoveScoutPro measured on the first launch of a large upgraded store (main-thread samples in +`sqlite3BtreeDropTable`/`clearDatabasePage`): freeing an index's pages is proportional to +its size, and with `secure_delete` on — SQLCipher's default — every freed page is written +back. On the 165 MB synthetic store, dropping three ~15 MB legacy indexes took 6–7 ms each +plain and 39–54 ms each with `secure_delete`; on a 1.8M-row, 3 GB production store the +four took 9 s through the library, and the six per-type rebuilds `CreateIndex` does for an +upgraded store — drop the whole-table index 4.x built, build the partial one — 9 s more +(0.7–4.7 s each). They stay on by default, because they make bulk writes faster: 25–45% +measured for 5.0 with the four built-ins alone, 2.1–3x on the production store once the +six whole-table per-type indexes go too (table below). +`autoOptimize: false` connects without the drops and records each `CreateIndex` whose +index 4.x built as pending, leaving that index to serve queries — about 140 ms for the +connect and six declarations on that store; `Optimize`/`OptimizeAsync` then do the drops, +the rebuilds, the orphan sweep a 4.x rollback needs, the statistics delete, and a +compaction that returns the freed pages — 2 GB on that store — since a 4.x store has no +incremental auto-vacuum and nothing else can. The numbers are in the table below. Both +hold the single connection for the duration and run on the calling thread — +Microsoft.Data.Sqlite executes synchronously, so the async form alone does not move the +work off the caller — so apps call them from a background thread. + +The compaction is `VACUUM INTO` a copy next to the database, then a swap: the connection +closes, the copy is renamed over the file, and the connection reopens on it. A full +`VACUUM` writes the data twice — into a temp copy, then back into the file through the +WAL, which grew to 1.04 GB on the 2.37 GB store — so it needs free space for about two +compacted copies and, on a 49 MB store with 75 MB free, failed with `database or disk is +full`, left `temp_store = FILE` on the connection, and was retried on every call. `VACUUM +INTO` writes the live pages once, needs free space for one compacted copy, uses no temp +directory, and leaves the database untouched until the rename, which is atomic: the same +store compacted on the same volume. The `-wal` and `-shm` are deleted before the rename, +not after: SQLite checks a WAL only against its own header, so a WAL an interruption left +next to the new file would be replayed into it. `Optimize` checks the volume first and skips the +compaction, to retry on the next call, when the space is not there or SQLite reports the +disk full, and discards the copy when the WAL survives the close, which happens only +when the close could not checkpoint it. Under SQLCipher, whose `secure_delete` default zeroes every freed page through +the WAL — dropping a 528 KB index wrote 544 KB of WAL, against 12 KB with the setting off +— the drops run with it off when a compaction follows, and the setting is restored after. + +## Measured on the real store + +Through the library on a copy of a 4.4.2 production store (1,801,125 rows, 3,063 MB, eleven +indexes, no `TychoIndex`, `auto_vacuum` NONE), Release build, e_sqlite3 3.50.3, NVMe, the +file just copied so everything is warm. The lookups are the app's four: a pricing level by +brand, origin and load date; a distance by SPLC pair; a zip3; a zip. + +| `autoOptimize: false` | Time | +|---|---| +| Connect | 72 ms | +| Six `CreateIndex`, all recorded pending, no DDL | 69 ms (67 of it the first call's JIT) | +| Lookups while pending, on the 4.4.2 indexes | pricing 5.3 ms, SPLC 0.2 ms, zip3 and zip 0.05 ms | +| `Optimize()`: four drops, six rebuilds, 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 record it pending, 15 ms for `Optimize()` to rebuild it, 9 ms inline. + +The compaction that replaced the full `VACUUM`, measured through the library on a copy of +another 4.4.2 pricing store (1,763,583 rows, 2,374 MB, the same eleven indexes, e_sqlite3 +3.50.3, NVMe, warm): `Optimize()` under `autoOptimize: false` — the four drops, six +rebuilds, `VACUUM INTO` and the swap — 19.0 s, against 22.4 s with the full `VACUUM` on +the same store, the file 2,374 MB → 1,037 MB with +the WAL never above 12 MB where the full `VACUUM` had taken it to 1,043 MB; lookups on +the swapped-in file 0.56 / 0.05 / 0.04 / 0.04 ms without reconnecting; the next launch's +`Optimize()` 1.5 ms. The same 49 MB store on a volume with 75 MB free: the full `VACUUM` +failed with the disk full, the compaction took 153 ms; with 16 MB free it was skipped in +2.5 ms, the store untouched and in use. Through SQLCipher with a key, the compaction of +that store took 1.4 s and the copy opened under the same key with `secure_delete` back on. + +Cold: the same runs with the file copied without caching (`F_NOCACHE`; a system purge +needs root), verified cold by a first sequential read at half the cached speed. Every phase +was within noise of the warm run — deferred connect 78 ms and declarations 62 ms, first +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: 381 passed, 4 skipped, 0 failed in both configurations (Debug 2 s, + Encrypted 1 m 30 s), the eight new tests in `OptimizeTests.cs` and + `ConfigurationTests.cs` included. 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 diff --git a/planner-statistics-history.md b/planner-statistics-history.md new file mode 100644 index 0000000..c6edb02 --- /dev/null +++ b/planner-statistics-history.md @@ -0,0 +1,206 @@ +# Query Planner Statistics: History and Decisions + +TychoDB stores every object in one table, `JsonValue`. Two kinds of index matter here: + +- **General index**: `(FullTypeName, Partition)`, shared by all types. +- **Per-type index**: a partial index that `CreateIndex` builds for one property of one type. + +SQLite's query planner chooses between them. If `ANALYZE` has stored statistics in `sqlite_stat1`, the planner uses them; if not, it uses its built-in rules. + +--- + +## 1. The 5.3.1 problem + +**What happened:** Lookups on an indexed property became slow on large stores. On a 1.68M-row store, a lookup took 82–366 ms instead of 0–1 ms. The results were still correct. + +**Why:** 5.3.1 ran `ANALYZE` with `analysis_limit = 400`, so SQLite read only the first 400 entries of each index. That sample told the planner each type had about 81 rows, but the largest type had 586,986. So the planner picked the general index and read every row of the type on each lookup. + +--- + +## 2. First fix: full statistics + +**Changed:** `ANALYZE` ran without a limit after `CreateIndex`, and once on stores that already held sampled statistics. + +**Why:** Full statistics give the planner the right row counts, so it picks the per-type index again. + +**Result:** Lookups were fast again, but a full `ANALYZE` took 3.2 s on the 1.68M-row store and 17.5 s on a 2.2 GB store. + +--- + +## 3. Connecting became slow + +**What happened:** On the first launch after upgrading, connecting took 10–34 s on MoveScoutPro's device stores. + +**Why:** Connecting did two slow things. It dropped four indexes that 4.x created and 5.x no longer needs, which took 3.8–9.3 s, and it ran the statistics work. + +--- + +## 4. Opt-out for the slow connect + +**Changed:** Added `autoOptimize: false`, plus `Optimize()` / `OptimizeAsync()` to do the same work later. + +**Why:** It lets an app connect fast and do the slow, one-time work on a background thread. + +--- + +## 5. `PRAGMA optimize` could not be trusted + +**What happened:** +- **Sampling came back:** by default, `PRAGMA optimize` limits `ANALYZE` to 2,000 rows, which recreated the 5.3.1 problem. +- **It re-analyzed on every call:** with the limit removed, it estimated a 1.84M-row store at 174,370 rows, so it decided the table had grown and re-analyzed on every call, 20–30 s each time. + +**Changed:** TychoDB stopped using `PRAGMA optimize`, and decided for itself when statistics were out of date. + +**Why:** SQLite's own check gave wrong answers on real data. + +--- + +## 6. Step back: no statistics at all + +**Changed:** All statistics work was removed. Connecting now deletes any statistics an earlier release left behind. The 4.x index drops stay. + +**Why:** +- **Each fix needed another fix,** so it was worth asking whether statistics were needed at all. +- **Built-in rules choose correctly without them.** The planner picks the right index for every single-index query TychoDB runs: equality, range, sort with a limit, an unindexed property, a whole type, and a count. +- **Nothing left to go wrong:** with no statistics, nothing can be sampled or go out of date. +- **The drops make writes faster:** bulk writes are 25–45% faster without the old indexes. + +**Known trade-off:** when a query filters on two indexed properties, the planner can't tell which index is better, so it picks one by rule. This was accepted without being measured. + +--- + +## 7. Tested on real device stores + +MoveScoutPro's test suite ran on four device stores (682k–1.85M rows, 2.4–3.2 GB), with `autoOptimize: false`: + +| | Stock 5.3.1 | This branch | +|---|---|---| +| First connect after upgrade | 10–34 s | 8–40 ms | +| `Optimize()`, first call | – | 3.8–9.3 s | +| `Optimize()`, later calls | – | 0–1 ms | +| App login to launch page | 18.2 s | 8.8 s (4.4.2: 9.3 s) | + +Results matched 4.4.2 for every read and write. + +--- + +## 8. Rename (later reset) + +**Changed:** `autoOptimize` became `dropLegacyIndexes`, and `Optimize()` became `DropLegacyIndexes()`. + +**Why:** At that point dropping the old indexes was the only work left, so the names should say that. + +**Now:** Reset off the branch. The branch keeps `autoOptimize` / `Optimize()`, which now do more than the drops (step 12). + +--- + +## 9. Commit 120fc5c: statistics come back + +**Why:** It found two real problems with step 6: + +1. **Two indexed filters:** the planner used whichever index was created last. That cost 4.6 ms instead of 0.02 ms at 40,000 rows. +2. **Writes on every connect:** each connect dropped and re-created `sqlite_stat1`, which changes the schema twice. With `persistConnection: false`, that happens on every operation. + +**Changed:** +- **Gathered on index build:** a full `ANALYZE JsonValue` ran whenever `CreateIndex` built an index. +- **General index overwritten:** its statistics were set to half the table's row count, so it only wins when one value covers more than half the table. +- **One-time repair:** stores with sampled statistics were fixed once, and `PRAGMA user_version` recorded that it had run. + +--- + +## 10. 120fc5c reverted + +**Why:** +- **Statistics never refreshed.** They were taken once, when an index was built. In two synthetic tests (544k rows) they went out of date and lookups took 174 ms and 180 ms instead of 0 ms. That's the 5.3.1 problem again, and nothing fixed it. +- **Upgrades got slower.** Every index build ran a full `ANALYZE`, which takes 3.2–17.5 s on real stores, and a 4.x upgrade rebuilds every index. +- **No gain on a real store.** On a 1.8M-row, 3 GB production store, plans and timings were the same with and without statistics. +- **Composite indexes cover two filters.** A query filtering on two properties is served by a composite index, which needs no statistics. The README now says so. + +**Kept:** the connect-write problem it found, fixed in step 11. + +--- + +## 11. Connecting writes nothing + +**What happened:** Connect wrote to the file every time, for two reasons: +- It dropped and re-created `sqlite_stat1`. +- It ran `PRAGMA auto_vacuum = INCREMENTAL`, which rewrites the first page of an existing store. + +**Changed:** +- **Statistics:** connect deletes leftover `sqlite_stat1` rows only when there are any, and never drops the table. +- **Auto-vacuum:** the pragma runs only for a new file. + +**Why:** A write on every connect is wasted work, and with `persistConnection: false` it happened on every operation. + +**Result:** Connecting to a current store leaves the file byte-identical. + +--- + +## 12. Defer the index rebuilds too + +**What happened:** On a 4.x upgrade, each first `CreateIndex` drops the old 4.x index and builds the new one. On a 1.8M-row, 3 GB store that took 0.7–4.7 s per index, 9.0 s for six, on top of 9.2 s of drops at connect. + +**Changed:** +- **Pending indexes:** with `autoOptimize: false`, `CreateIndex` marks the index as pending, and the old 4.x index keeps serving queries. +- **`Optimize()` does the rest:** the drops, the pending rebuilds, and a `VACUUM` to return the freed space. 4.x stores never got incremental auto-vacuum, so the space can only come back this way. +- **Two related fixes:** + - The string overload of `CreateIndex` no longer keeps the 4.x index by mistake. + - Indexes a 4.x rollback recreated are dropped. + +**Result** on that store: + +| | | +|---|---| +| Connect plus six `CreateIndex` | about 140 ms | +| `Optimize()` | 26.3 s | +| File size | 3,063 MB → 1,030 MB | +| Next launch: connect, six `CreateIndex`, `Optimize()` | 44 ms, 34 ms, 1 ms | +| Bulk writes afterwards | 2.1x faster (indexed type), 3x (unindexed) | + +--- + +## 13. Compact with `VACUUM INTO` instead of `VACUUM` + +**What happened:** A full `VACUUM` writes the data twice: into a temp copy, then back through the WAL, which grew to 1.04 GB on a 2.37 GB store. It needs room for about two copies. On a 49 MB store with 75 MB free it failed with "database or disk is full", and was retried on every call. + +**Changed:** `Optimize()` now: +1. writes a compacted copy with `VACUUM INTO`, +2. closes the connection, +3. deletes the old `-wal` and `-shm` files, +4. renames the copy over the database, +5. reopens. + +It skips the compaction, and retries on the next call, when there isn't room or a WAL with data is still there after the close. + +**Why:** +- **One copy:** `VACUUM INTO` writes the data once, so it only needs room for one compacted copy. +- **Safe interruption:** the database isn't touched until the rename, which is atomic. +- **WAL first:** SQLite would replay an old WAL into the new file, so the WAL is deleted before the rename. + +**Result:** + +| Store | Full `VACUUM` | `VACUUM INTO` | +|---|---|---| +| 1.76M rows, 2,374 MB: whole `Optimize()` | 22.4 s | 19.0 s | +| Same store: largest WAL | 1,043 MB | 12 MB | +| 49 MB store, 75 MB free | failed, disk full | 153 ms | +| 49 MB store, 16 MB free | – | skipped in 2.5 ms | + +--- + +## 14. Smaller fixes + +- **Both overloads, one name:** when the same index name is declared through both `CreateIndex` overloads, each now leaves the other's index alone. Before, one dropped and rebuilt the other's index on every launch. +- **Pending definitions are checked:** a pending index's saved definition is rebuilt from its parts and compared exactly before `Optimize()` runs it, and anything else is refused. It's read back from the file, so it could have been changed. +- **Read-only files:** connecting works even when leftover statistics can't be deleted. +- **Version:** set to 5.4.0. + +--- + +## Where it ends up + +- **No statistics:** no planner statistics are gathered, and connect deletes leftover ones only if there are any. +- **Quiet connect:** connecting to a current store writes nothing. +- **`autoOptimize: true` (default):** connect drops the 4.x indexes and `CreateIndex` rebuilds on the spot. +- **`autoOptimize: false`:** connect and `CreateIndex` take milliseconds, and `Optimize()` on a background thread does the drops, rebuilds and compaction. +- **Two filters:** filtering on two properties needs a composite index.