Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2a0a399
fix: gather full planner statistics instead of sampled ones
arotolo Oct 9, 2026
f3023f5
fix: repair sampled statistics left by earlier releases on first connect
arotolo Oct 9, 2026
f7ee589
feat: add autoOptimize opt-out and Optimize()/OptimizeAsync()
arotolo Oct 9, 2026
ae6a6af
fix: make PRAGMA optimize consider JsonValue on SQLite before 3.46
arotolo Oct 9, 2026
fa8f79f
docs: describe the sampled-statistics regression, its repro and the fix
arotolo Oct 9, 2026
dbef355
fix: derive the user_version stamp from its constant
arotolo Oct 10, 2026
ed0da4b
fix: decide statistics staleness from an exact row count, not PRAGMA …
arotolo Oct 10, 2026
93a0a04
refactor: stop gathering planner statistics
arotolo Oct 10, 2026
8e8a0b9
fix: remove the planner statistics earlier releases left behind
arotolo Oct 10, 2026
322be81
docs: describe why TychoDB gathers no planner statistics
arotolo Oct 10, 2026
120fc5c
fix: gather full planner statistics at index creation and pin the gen…
michaelstonis Oct 10, 2026
c0946fc
Revert "fix: gather full planner statistics at index creation and pin…
arotolo Oct 15, 2026
86917c7
fix: open an existing store without the creation-only auto_vacuum pragma
arotolo Oct 15, 2026
8d71dcb
fix: delete leftover planner statistics at connect instead of droppin…
arotolo Oct 15, 2026
a12be37
feat: defer index migrations under autoOptimize:false and widen Optimize
arotolo Oct 15, 2026
6a33cc0
docs: describe the 5.4.0 upgrade path, Optimize and the statistics re…
arotolo Oct 15, 2026
1c149c4
docs: cite the upgrade timings measured through the library on the 1.…
arotolo Oct 15, 2026
e19ae95
docs: add the bulk-write and cold-cache figures measured on the 1.8M-…
arotolo Oct 15, 2026
53c7f84
fix: keep a legacy-named index that another declaration records as it…
arotolo Oct 20, 2026
6063b04
fix: run a pending index definition only if it rebuilds byte for byte
arotolo Oct 20, 2026
05c29e5
fix: compact a store with VACUUM INTO and a file swap instead of a fu…
arotolo Oct 20, 2026
4e82c76
fix: connect to a read-only store when the leftover statistics cannot…
arotolo Oct 20, 2026
37d05af
fix: set the package version to 5.4.0
arotolo Oct 20, 2026
9af4232
docs: describe the compaction swap, the definition check and the read…
arotolo Oct 20, 2026
be39d8a
docs: add the history of the planner statistics work and the reasons …
arotolo Oct 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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_<name>_<Type>` next to the 5.x `idx_<name>_<Type>_<hash>`, 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
Expand Down
2 changes: 1 addition & 1 deletion Directory.build.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<LangVersion>latest</LangVersion>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<Version>5.0.0</Version>
<Version>5.4.0</Version>
</PropertyGroup>
<PropertyGroup>
<Authors>Eight-Bot, Inc.</Authors>
Expand Down
58 changes: 52 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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<Person>(x => x.Age, "age_index");
await Task.Run(() => deferredDb.Optimize());
```

### Device Performance Profiles
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion TychoDB.Benchmarks/Diagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 ----
Expand Down
11 changes: 11 additions & 0 deletions TychoDB.UnitTests/ConfigurationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Loading
Loading