Research notes / Database recovery
Why SQLite index results can change when database bytes do not
Published 18 October 2026; updated 2026-11-19 / Controlled software experiment and source synthesis
A database checksum can stay identical while an indexed query returns a different answer from a table scan. In two constructed SQLite cases, changing a runtime callback caused that disagreement, and quick_check still returned ok. Recovery needs compatible interpretation, not just intact bytes.
On this page23 sections
Same file, different runtime, different answer
Each fixture had three rows and one index. Copies opened with the original, missing and changed callback had exactly the same SHA-256. All observations opened those copies read-only; hashes before and after each observation also matched. The rebuilt copies were intentionally modified.
| Index / runtime | Indexed IDs | Scan IDs | Quick | Full |
|---|---|---|---|---|
| Function Original callback | 2 | 2 | ok | ok |
| Function Changed callback | None | 2 | ok | Issues |
| Function Changed + rebuilt | 2 | 2 | ok | ok |
| Collation Original callback | 2, 3 | 2, 3 | ok | ok |
| Collation Changed callback | 1, 2, 3 | 1, 2 | ok | Issues |
| Collation Changed + rebuilt | 1, 2 | 1, 2 | ok | ok |
The function fixture stored values 1, 2 and 3. Its original score(x)=x became score(x)=x+100, under the same SQL name. The changed-runtime query for score 102 should select row 2. The table scan did; the old index returned no rows.
The text fixture stored ant, bee and cat as rows 1, 2 and 3. Its named comparator changed from ascending to descending ASCII order. For value COLLATE APP_ORDER >= 'bee', the new comparison admits ant and bee. The old index also returned cat. This is a changed comparison rule, not an alphabetical-order claim.
INDEXED BY idx and NOT INDEXED force the two access paths. The recorded query plans show which path ran. Explicit expected answers, derived from the fixture rules, prevent agreement between two wrong queries from passing the test.
The two missing-callback controls failed the queries explicitly. A missing function still allowed quick_check to return ok; a missing collation made both checking commands fail. A checking error is not an empty diagnostic list or a successful check.
An index preserves assumptions about computation
An expression index stores computed keys. SQLite requires functions used there to be deterministic across the database's lifetime, not merely repeatable within one connection. Tagging an application function deterministic is a promise; it does not make incompatible implementations agree. [3] [2]
A collation supplies comparison behavior to a connection. Its name does not identify a preserved implementation version. These fixtures deliberately changed the promised semantics without rebuilding the old index. They demonstrate a documented compatibility hazard, not a newly discovered SQLite defect. [1]
quick_check omits UNIQUE verification and the comparison of index contents with table contents. Full integrity_check reported missing index entries in both changed-runtime cases. The different outcomes follow the check scopes; neither a file hash nor a quick check tests every runtime dependency. [5]
Agreement is not the same as a correct answer
Rigger and Su's OSDI 2020 paper, Testing Database Engines via Pivoted Query Synthesis, constructs queries that must include a chosen row. Its independent expression evaluator supplies an expectation instead of treating agreement between engines as proof. The paper also explains the boundary: row containment alone cannot validate result cardinality or ordering. [7]
Here the small, explicit fixtures let us check the entire ordered answer, including extra and missing rows. The callback rules define that answer outside the index. This is a manually specified oracle, not a SQLancer run or a reproduction of the paper's bug-finding campaign. Disagreement after deliberately changing index assumptions is not evidence of an optimizer defect.
Small platform changes can matter too
SQLite's current stale-index documentation describes less dramatic sources of drift: math-library differences, ICU changes and revised numeric conversions. It describes such cases as uncommon. Our large, deliberate changes expose the mechanism clearly; they do not measure those real-world changes or their frequency. [4]
Version scope matters. That documentation says SQLite 3.53.0 added repair of some stale expression entries during row updates or deletion, while integrity checking still reports stale entries. It does not establish that opening or querying every incompatible database repairs it. The recorded experiment used 3.45.1 and did not test the newer behavior. [4]
Key order, access paths and unique combinations
A composite index has more than one key column or expression. In a B-tree on (region, seq), entries are ordered by region, then by seq within equal regions. That does not give a global seq order across regions. A query must still request its order explicitly. [70]
The leftmost-prefix rule describes an ordinary bounded lookup, not an absolute ban on suffix queries. A skip scan can search distinct leading-key groups. PostgreSQL 18 also documents suffix filtering and cost-based skip scans: a condition after a range is not automatically useless. These planner choices depend on the engine and statistics. [71] [73]
Same answers, different plans after ANALYZE
The constructed fixture contains two regions, a and b, each with seq values 0 through 199. The 400 rows have IDs 1 through 400 and one index on (region, seq). No index hint forces the observed paths. Before ANALYZE, the suffix-only query used a table scan; afterward it used a covering skip scan. Both returned IDs 124 and 324. The index was already present in both states.
| Query / state | IDs | Observed plan |
|---|---|---|
| seq = 123 / before ANALYZE | 124, 324 | SCAN samples |
| seq = 123 / after ANALYZE | 124, 324 | SEARCH samples USING COVERING INDEX by_region_seq (ANY(region) AND seq=?) USE TEMP B-TREE FOR ORDER BY |
| region = a, seq >= 198 / ORDER BY seq | 199, 200 | SEARCH samples USING COVERING INDEX by_region_seq (region=? AND seq>?) |
| region >= b, seq = 123 / ORDER BY id | 324 | SEARCH samples USING COVERING INDEX by_region_seq (ANY(region) AND seq=?) USE TEMP B-TREE FOR ORDER BY |
| All regions / ORDER BY seq, region / LIMIT 4 | 1, 201, 2, 202 | SCAN samples USE TEMP B-TREE FOR ORDER BY |
Fixing region allowed the recorded plan to satisfy the seq range and ordering without a separate sort. Ordering all rows by seq, region instead required a temporary sorting B-tree in this capture. A plan reports the selected strategy; it does not establish a speedup. SQLite warns that EXPLAIN QUERY PLAN formatting can change. The replay tests complete answers independently of those descriptions. [76]
The whole query matters, not just the lookup. Selinger and colleagues' System R paper retained the cheapest plan for each useful output ordering as well as the cheapest unordered plan. An ordered access path could beat a cheaper unordered lookup once the required sort was included. For joins, useful orderings could also avoid a sort before a merge. This 1979 optimizer design explains why key order deserves its own cost comparison; it is historical context, not evidence that today's SQLite uses the same optimizer or that our fixture measures those costs. [77]
Uniqueness and separate indexes are different questions
Adding UNIQUE(region, seq) accepted the fixture even though every seq appeared twice. An attempted second ('a', 123) was rejected; ('a', 200) was accepted. The rule constrains the pair. This fixture forbids NULL; SQLite's distinct-NULL behavior and PostgreSQL's optional NULLS NOT DISTINCT need separate consideration. [72] [75]
UNIQUE and a duplicate-group audit ask different questions
A text key uses its configured comparison rules, not necessarily bytewise identity. With SQLite's built-in NOCASE on region, ('A', 1) and ('a', 1) conflict, while ('a', 2) can coexist. BINARY accepts both case variants. NOCASE folds ASCII letters only: the supplied U+00C4/U+00E4 pair remains distinct. [Unique keys] [Collation rules]
NULL adds a separate distinction. The nullable fixtures accept two copies of ('A', NULL), (NULL, 1) and (NULL, NULL). Their UNIQUE constraint remains satisfied, but GROUP BY region, seq HAVING count(*) > 1 returns three groups. SQLite groups NULLs together while treating them as distinct for uniqueness. The full integrity check returns ok in every fixture. [Grouping rules] [NULL uniqueness]
| Text comparison / keys | Accepted | UNIQUE errors | NOT NULL errors | Duplicate groups |
|---|---|---|---|---|
| BINARY / Nullable | 11 | 1 | 0 | 3 |
| NOCASE / Nullable | 10 | 2 | 0 | 3 |
| BINARY / Required | 5 | 1 | 6 | 0 |
| NOCASE / Required | 4 | 2 | 6 | 0 |
Both required-key fixtures reject all six NULL-bearing attempts. NOT NULL rejects missing values; it does not choose the application's identity policy. A duplicate-group audit is an application-policy check, not a direct reimplementation of UNIQUE. PostgreSQL's NULLS NOT DISTINCT is a separate documented option, not an engine tested here. [NOT NULL] [PostgreSQL option]
Inspect the 48 complete insertion states, generated summary, native replay, known-answer tests and method and reproduction notes. Each attempt checks all stored rows, their types and exact errors; rejected writes must leave prior rows unchanged. These INSERT controls do not test updates, concurrency, durable-file recovery or timing. For changed application collations, see the separate rebuild and migration controls.
Two separate single-column indexes are not a composite structure. PostgreSQL can combine row-location bitmaps, losing their original index ordering; SQLite does not generally use AND-by-intersection. Choose key order and access paths for actual predicates and ordering requirements, not a universal claim that one arrangement is fastest. [74] [70]
Download the native replay, known-answer tests, complete observations and run instructions into one directory.
python3 -B replay.py --check results.json
python3 -B -m unittest -v test_replayCaptured 18 November 2026 with Python 3.12.3. Five dependent query observations, then a uniqueness control, all in one fresh in-memory database. No concurrency, crash, durable-file recovery, elapsed-time benchmark or PostgreSQL execution. The earlier runtime-callback experiments remain separate.
A partial index constrains selected rows, not the whole table
A partial index adds a membership predicate to an index. In SQLite, only a true predicate includes a row; false and NULL exclude it. This is not a partially written or damaged index. [Partial indexes]
CREATE TABLE items(
id INTEGER PRIMARY KEY,
label TEXT NOT NULL,
active INTEGER
);
CREATE UNIQUE INDEX one_active
ON items(label) WHERE active = 1;Here label is the key and active controls membership. Our constructed rows share group-a: row 1 starts active, row 2 inactive and row 3 has NULL activity. The duplicate labels coexist. Inserting another active copy or activating row 2 fails without changing those rows; deactivating row 1 lets row 2 enter the subset.
| Step | Outcome | Selected IDs |
|---|---|---|
| included | Accepted | 1 |
| excluded false | Accepted | 1 |
| excluded null | Accepted | 1 |
| duplicate included | SQLITE_CONSTRAINT_UNIQUE | 1 |
| promote conflict | SQLITE_CONSTRAINT_UNIQUE | 1 |
| leave subset | Accepted | None |
| promote after release | Accepted | 2 |
The key is deliberately NOT NULL: NULL in an index key is a separate uniqueness question from NULL in its predicate. SQLite treats NULL keys as distinct. The fixture verifies the full table after every step and after reopening; it does not infer preservation from selected IDs alone. [Unique keys]
To inspect the excluded rows, do not simply negate the predicate. On the initial three-row state, WHERE NOT(active=1) returns only row 2: row 3 still evaluates to NULL. WHERE (active=1) IS NOT TRUE returns both rows 2 and 3. The accompanying tests check this complete complement and separately allow two NULL keys inside a nullable-key unique index. [Boolean expressions]
Eligibility is not a promise to choose the index
A query must imply the predicate in a form the planner recognizes. SQLite documents limited rules, not general algebraic proof. Its ban on bound parameters concerns the index definition, not all queries: an equality comparison with a parameter can use an IS NOT NULL partial index. The supplied control requires that path with INDEXED BY; it does not measure the optimizer's unforced choice. [Planner rules]
PostgreSQL likewise checks implication at planning time. Do not turn its warning about unknown parameter values into a ban on every prepared statement: its generic plans retain parameters, while custom plans incorporate supplied values. This qualification combines two documentation pages; no PostgreSQL execution is claimed here. [PostgreSQL predicate] [Prepared plans]
Membership is another runtime dependency: SQLite requires deterministic predicate functions, and falsely labeling a changing function deterministic can invalidate the index. A readable database file does not preserve that function's implementation. [2]
A smaller index still has a maintenance cost
Stonebraker's 1989 The Case for Partial Indexes weighs read savings against the frequency and cost of indexed updates. It also proposes using predicates to track incrementally built or rebuilt index regions, with extra optimizer support. These are design and cost-model arguments, not measurements of a current SQLite or PostgreSQL release. [1989 report, sections 3.1-3.4]
Do not infer that many disjoint partial indexes automatically act like partitions. PostgreSQL documents that the planner tests their applicability separately rather than understanding their collective coverage. Choose the subset from the actual query and update workload, then examine plans; a reduced entry count alone does not establish a faster application. [Partial indexes and partitioning]
Inspect the complete observations, standalone capture and known-answer tests. All writes use a fresh temporary database. Single writer, autocommit statements, no crash, concurrent-write, space-saving or speed claim.
An intact RTree can omit an exact time interval
Missing answers do not require changed callbacks or stale entries. In a separate SQLite RTree fixture, the exact source interval [1800000001,1800000002] seconds was stored as [1800000000,1800000256]. Unexpanded containment in the original one-second query window returned no row, while both rtreecheck and integrity_check returned ok. The synchronized index had a coarser coordinate representation, not a damaged file.
Containment here includes equality: the source lower bound must be at least the query lower bound, and the source upper bound at most the query upper bound. No strict-inequality exclusion is intended. SQLite documents rtreecheck checks for coordinate ordering, parent enclosure and consistency of internal node, parent and row-ID mappings. Those checks do not compare answers with a separate authoritative source table. [29]
SQLite documents binary32 floating-point RTree coordinates, with lower bounds rounded downward and upper bounds upward. This protects overlap searches against that rounding mechanism but can exclude boundary cases from contained-within searches. Ordinary SQLite INTEGER and REAL storage have different representations; declaring an RTree coordinate column INTEGER does not change its module's coordinate type. [29] [31]
At this epoch magnitude adjacent binary32 values are 128 seconds apart. The versioned rtreeValueUp implementation first converts to binary32 and, if the result is inward, adjusts the original binary64 value before converting again. Our source-derived calculation matches the observed upper bound. The 256-second envelope is specific to this input and implementation, not a universal error bound. [30]
| Coordinate contract | Exact source bounds | Stored index bounds | Unexpanded containment IDs | Overlap + exact IDs |
|---|---|---|---|---|
| Unix seconds seconds | 1800000001 to 1800000002 | 1800000000 to 1800000256 | None | 1 |
| Negative seconds seconds | -1799999999 to -1799999998 | -1800000000 to -1799999744 | None | 1 |
| Unix milliseconds milliseconds | 1800000000001 to 1800000000002 | 1799999979520 to 1800000241664 | None | 1 |
| Integer precision boundary integer units | 16777217 to 16777218 | 16777216 to 16777218 | None | 1 |
| Relative seconds seconds Origin: 1800000000 | 1800000001 to 1800000002 | 1 to 2 | 1 | 1 |
| Relative milliseconds milliseconds Origin: 1800000000000 | 1800000000001 to 1800000000002 | 1 to 2 | 1 | 1 |
| Signed-int32 seconds seconds | 1800000001 to 1800000002 | 1800000001 to 1800000002 | 1 | 1 |
| Representable seconds seconds | 1800000128 to 1800000256 | 1800000128 to 1800000256 | 1 | 1 |
A complete candidate set must come first
For a nonempty closed source interval I, an enclosing index interval B and a query interval Q: if I lies inside Q, then B overlaps Q because both contain I. Overlap is therefore a complete candidate condition for exact source containment under these assumptions. Rechecking authoritative source values removes extra candidates. It cannot restore a row already excluded by unexpanded index containment; that rechecked-containment control still returned no row.
SELECT s.id
FROM idx AS r CROSS JOIN source AS s ON s.id = r.id
WHERE r.lo <= :query_hi AND r.hi >= :query_lo
AND s.lo >= :query_lo AND s.hi <= :query_hi
ORDER BY s.id;This is the tested unshifted-coordinate query. For relative coordinates, shift the index query bounds by the same retained origin, while comparing exact source values in their original units. Keep index maintenance synchronized with source changes. The proof assumes nonempty closed intervals and enclosing stored bounds; it does not certify arbitrary geometry or inconsistent coordinate conversions.
In the epoch-seconds empty-window control, overlap admitted rows 1 and 2 but exact rechecking correctly removed both. Across all sixteen designed windows the final answer matched the independently specified source answer. These selected controls do not estimate a real-world miss rate, and recorded query plans are not a performance benchmark.
The word containment also appears in Rigger and Su's Pivoted Query Synthesis, but means membership of a known row in a result set, not geometric containment. Their oracle does not establish result cardinality. Here we compare complete ordered ID lists for the small fixtures, including empty-window controls; this is not a PQS run or evidence of a new engine bug. [7]
Neither a smaller origin nor padding is an unlimited guarantee
The two small relative-coordinate controls and the in-range rtree_i32 seconds control retained exact target bounds. Neither is a universal migration recipe: preserve units, origin and range, and reject values outside signed 32-bit coordinates before using that variant. The separate padding probe found that one literal binary64 implementation of the documented relative expansion still missed this constructed row. This does not establish failure of every outward-quantized strategy or current SQLite release. [29] [32]
Download the self-contained reproduction package, complete native observations, generated table data, reproduction and version notes, and public-download checksums. The package retains source snapshots, code, original tests and checksums. It uses private temporary databases and refuses to overwrite results.
Recorded 2026-10-28 on Python 3.12.3, SQLite 3.45.1, Linux x86-64. One distribution build; its source ID is retained, and upstream source is not claimed byte-identical. No concurrent writer, crash, hardware fault, multidimensional geometry or latest-release reproduction. This is documented representation behavior, not a newly discovered engine defect.
Rebuilding cannot choose new application meaning
With the changed callback registered, REINDEX main.idx restored agreement in both three-row fixtures and full checks returned ok. SQLite documents rebuilding for changed collations and expression functions. The schema-qualified index name selects one object and avoids confusion with a collation of the same name. [6]
A separate two-row control explains why this is not a universal repair recipe. A UNIQUE index originally distinguished A and a. Under a new ASCII case-insensitive comparator, they became equal. quick_check returned ok, full checking reported a non-unique entry, and targeted rebuilding failed with SQLITE_CONSTRAINT_UNIQUE (2067).
The experiment rolled back that attempt and verified both original rows and the original file hash. Resolving this collision requires an application decision about identifiers or duplicate records. A rebuild cannot make two newly equal keys unique without changing data or the rule.
For an upgrade or restore, preserve the original, identify the callback implementations and dependent indexes, and test a disposable restored copy under the intended runtime. Treat a callback change as a migration: examine collisions before rebuilding, validate full check results, then run application acceptance queries. Do not rewrite an archival original merely to silence a diagnostic.
This adds an interpretation dependency to the existing backup verification analysis. A successful copy can preserve every byte and still require application code, comparison rules and their versions to reproduce the intended answers.
Stored generated values survive an index rebuild
Rebuilding an index is not enough when the old computation is stored in the table itself. In seven additional controls, all full integrity checks returned ok. Yet opening a copy with a changed function, rebuilding its index, and using the backup API all retained the old generated values. Replaying SQL under the changed function recomputed them instead.
The three-row table contains x, stored AS(score(x)) STORED and virtual AS(score(x)) VIRTUAL, plus an index on stored. The original callback is score(x)=x; the replacement is score(x)=x+100. Both are deliberately registered under the same name as deterministic. This breaks the schema's stability assumption; it is not a newly discovered engine defect. [2]
| Operation / callback | Stored | Virtual | Mismatched rows |
|---|---|---|---|
| Original / original | 1, 2, 3 | 1, 2, 3 | 0 |
| Reopen / changed | 1, 2, 3 | 101, 102, 103 | 3 |
| REINDEX / changed | 1, 2, 3 | 101, 102, 103 | 3 |
| Backup / changed | 1, 2, 3 | 101, 102, 103 | 3 |
| SQL replay / original | 1, 2, 3 | 1, 2, 3 | 0 |
| SQL replay / changed | 101, 102, 103 | 101, 102, 103 | 0 |
| Update row 2 / changed | 1, 102, 3 | 101, 102, 103 | 2 |
SQLite computes a STORED column on writing a row and a VIRTUAL column on reading it. An index on the stored result is an ordinary column index. Rebuilding that index does not itself rewrite the table's generated values. [8] [6] In our changed-runtime control the file hash stayed identical, but stored values differed from a fresh evaluation of the same expression.
A page copy and SQL replay preserve different things
The backup API copy reached SQLITE_DONE with zero remaining pages. After closing and reopening under the replacement callback it retained stored values 1, 2, 3, while the virtual column returned 101, 102, 103. The API copies database content; it does not migrate application function implementations. [9]
The recorded Python iterdump() output contains the schema and inserts only the ordinary inputs, for example INSERT INTO "sample" VALUES(2,2). Replaying the same SQL with the original callback preserved 1, 2, 3; with the replacement it produced 101, 102, 103 in both generated columns. This comparison concerns that recorded dump implementation, not every export tool. [10]
Finally, UPDATE sample SET x=x WHERE id=2 on a private copy recomputed only row 2, leaving stored values 1, 102, 3. This illustrates a mixed-generation table after a seemingly value-preserving update. It is a diagnostic control, not a recommended migration procedure.
Inventory the expressions before recovery
PRAGMA table_info reported only id and x in this fixture. table_xinfo exposed all four columns, with generated-column flags 3 for stored and 2 for virtual. SQLite documents that distinction. [11] An inventory using only the former can miss this dependency before choosing a recovery method.
Our engineering conclusion: decide whether recovery must preserve historical computed values or deliberately recompute them. Retain compatible function code, inspect generated expressions and dependent constraints, and compare complete application results on a disposable restored copy. A structurally valid database cannot choose that policy for you.
Corpus definition, reproduction script and complete observations. The latter include SQL, source identity, hashes, backup completion and query plans. All reads follow closing and reopening the files; the original remains unchanged.
python3 observe.py --work-root . --output generated-results.jsonRecorded 2026-10-18 on Python 3.12.3. Closed DELETE-journal fixtures only: no concurrent writer, WAL, crash or power loss. These seven designed cases do not estimate failure frequency or test newer SQLite versions.
A rebuilt file can preserve a stale computation
A successful SQL copy need not evaluate each generated expression. In a separate two-build experiment, completed backups, VACUUM INTO and a compatible-schema INSERT SELECT * preserved an already stale STORED value. The destination still passed integrity_check. An explicit projection of ordinary input columns recomputed this fixture instead.
The source has two rows and derived AS(hex(payload)), tested separately as STORED and VIRTUAL. A native incremental BLOB write on the recorded SQLite 3.45.1 build changes row 1 from AAAA to BAAA without maintaining the derivation; row 2 remains CCCC. SQLite 3.54.1 rejects that generated-table BLOB open. Both builds then copy the closed, older-build input. This is historical inconsistent data, not a claim that the newer engine accepts the original write. [Maintainer history] [Newer guard]
| Copy path | STORED value / full check | VIRTUAL index / full check |
|---|---|---|
| Backup API | 41414141 ok | No row Index mismatch |
| VACUUM INTO | 41414141 ok | No row Index mismatch |
| INSERT SELECT * | 41414141 ok | No row Index mismatch |
| Explicit inputs | 42414141 ok | Row 1 ok |
| WHERE 1: rejected | No rows ok | No row ok |
The rejected last row is not a completed copy: adding WHERE 1 disables the special transfer path, and the INSERT supplies four values for three insertable columns. Its empty destination passes the check but fails completeness. Healthy SQL UPDATE seeds stayed consistent through all four successful copy paths.
Why INSERT and VACUUM can carry the old answer forward
The versioned INSERT implementation has a compatible-schema optimization that transfers raw table and index records. VACUUM creates matching tables and indexes before using star transfers. The standalone star-copy bytecode records raw-record operations without expression evaluation; the explicit-column control evaluates hex(payload). Its bytecode names the one-argument function hex(1); that notation does not mean the SQL literal hex(1) was evaluated. [Bytecode display] This explains the measured contrast, not every possible INSERT plan. [3.45.1 INSERT] [3.54.1 INSERT] [VACUUM source]
-- Separate controls; recovered.objects already has the matching schema.
INSERT INTO recovered.objects SELECT * FROM main.objects;
INSERT INTO recovered.objects(id,payload,label)
SELECT id,payload,label FROM main.objects NOT INDEXED;For STORED, the table and index agree on the old value but violate derived = hex(payload). For indexed VIRTUAL, a scan computes the current value while the stale index misses row 1; full checking detects that mismatch, but quick_check does not. Verify the expression independently and test the query path consumers use. The earlier callback experiment changed runtime meaning; this experiment keeps built-in hex() unchanged.
Copy fidelity, recomputation and completeness are different policies
The PQS paper explains why agreement between implementations is not a correctness oracle: both may share the same error. Its pivot-row test checks containment, not the whole answer. [7] In this recovery fixture, two readers agreeing on an old STORED value would miss the problem. We instead compare the complete rows with expectations derived from the original inputs and the unchanged expression. This is a hand-specified acceptance test, not a SQLancer campaign.
The backup controls reached SQLITE_DONE, zero remaining pages and successful finish. Their copies faithfully retained the inconsistent source. Neither this completion nor VACUUM's logical-copy contract promises application repair. [Backup API] [VACUUM contract] Preserve the original, decide which inputs and derived values are authoritative, and compare complete expected rows on a disposable output. Explicit projection is a fixture control, not a migration recipe for arbitrary triggers, constraints, collations or functions.
Test inherited values, not only the writer
A smaller corroborating fixture checks the same legacy-state distinction through both read-only and read/write connections. Its input changes from AA to BA; STORED hex(payload) remains 4141, while fresh evaluation returns 4241. Both full checks return ok. The recorded 3.54.1 build blocks new generated-table BLOB handles but still reads this inherited state. This supplements the earlier four-byte experiment; it is not a newly discovered defect. [RO/RW evidence]
On a disposable copy of the supplement's item table, this query returns row 1 after reopening, REINDEX, completed backup and VACUUM INTO. It returns no rows after explicit input projection or rewriting the input. Those operations recompute this expression but retain BA; they do not recover historical AA. Choose the intended inputs before considering repair.
-- Diagnostic for this fixture; no data is changed.
SELECT id, hex(payload) AS current_hex, stored
FROM item NOT INDEXED
WHERE stored IS NOT hex(payload)
ORDER BY id;A successful query returning no mismatches establishes only this expression invariant for the rows still present. Missing rows, or a different input paired with its correctly recomputed value, can also pass. Compare the expected identifiers and input bytes against a trusted recovery reference separately. This is a limitation of the diagnostic, not a measured failure rate. The PQS paper likewise distinguishes partial-result oracles from validation of result cardinality. [7]
The supplement's method and limits, 24 recovery outcomes and offline replay package retain two exact closed input images, two recorded reader builds and both source journal settings. This tests a chosen expression invariant, not arbitrary schemas, historical authenticity, crash safety or incident frequency.
Read the reproduction guide, full method and limits, evidence-linked findings and complete code/data package. The source receipts, exact binaries' identities, query bytecode and both captures are retained.
160 designed configurations: 128 completed copies and 32 expected SQL rejections. Two processors, two journal settings, STORED/VIRTUAL, index present/absent, historical-BLOB/healthy-UPDATE seeds, five paths. Closed synthetic files; WAL configured but no concurrent writer, crash or power-loss test. Fresh same-host replay matches the retained observations. No incidence estimate, first-fixed-release claim, new vulnerability or independent researcher replication.
An aborted BLOB write can leave a committed prefix
A failed chunk write need not restore the previous object. In the same-row expiration control, the application intended to replace AAAA with BCDE. It wrote BC, changed only the same row's revision column, then tried to write DE. That second write returned SQLITE_ABORT, yet the implicit path committed BCAA. Across ten designed schedules on SQLite 3.45.1 and 3.54.1, each in DELETE and WAL mode, all 40 final images passed integrity_check.
This is a different boundary from the generated-value experiment above: no generated columns, callbacks, indexes or triggers are involved. SQLite documents that an UPDATE to any column in the target row expires its BLOB handle; expiration does not undo completed earlier writes. Updating progress metadata can therefore interrupt an incremental payload write even when the SQL does not assign the payload column. [BLOB open] [BLOB write]
| Schedule / final action | Second write | Writer state | Observer payload | Final payload |
|---|---|---|---|---|
| Normal / commit | 0 | 2 | AAAA | BCDE |
| Same row / implicit | 4 | 0 | BCAA | BCAA |
| Same row / commit | 4 | 2 | AAAA | BCAA |
| Same row / rollback | 4 | 2 | AAAA | AAAA |
| Same row / rollback to | 4 | 2 | AAAA | AAAA |
| Other row / commit | 0 | 2 | AAAA | BCDE |
| Failed reopen / commit | 4 | 2 | AAAA | BCAA |
| Bounds error / commit | 1 | 2 | AAAA | BCAA |
| Bounds error / retry, commit | 1 | 2 | AAAA | BCDE |
| SQL payload replacement | 4 | 2 | AAAA | ZZZZ |
Handle lifetime is not transaction lifetime
In the implicit control, a fresh connection saw BCAA before sqlite3_blob_close(). The writer had already moved from WRITE to NONE; a later ROLLBACK failed because no transaction remained. In the two pinned implementations, the expired-write path finalizes the internal statement and clears its pointer. The allocated handle can outlive that statement. This explains the observed timing on these builds, not a rule that every SQLite error commits work. [Older implementation] [Newer implementation]
With explicit BEGIN, the same error left the transaction in WRITE. COMMIT preserved the prefix; ROLLBACK restored AAAA. ROLLBACK TO restored both the target payload and revision while keeping a sentinel revision of seven written before the savepoint. Transaction state describes an active database transaction, not application completeness; a savepoint defines the caller's partial-rollback boundary. [Transactions] [Savepoints]
The architecture overview by Gaffney and colleagues separates virtual-machine execution from journal-level transaction mechanisms (sections 2.1-2.2). Those mechanisms do not choose the application\'s replacement boundary across several BLOB calls. Read the API\'s error-specific guarantees alongside that overview: the controls show incomplete application work inside valid committed state, not a violation of transaction atomicity. [SQLite architecture, PVLDB 2022] [Incremental-write contract]
A retryable argument error and an aborted handle differ
The out-of-bounds attempt changed no bytes and left the handle usable: retrying at the correct offset completed BCDE. A failed reopen to a missing row instead aborted the handle; reopening it to the original row also failed. Its reported size became zero although the stored BLOB still contained four bytes. A successful close did not erase those earlier errors. [Write bounds] [Reopen] [Close]
For an all-or-nothing replacement, establish the owned transaction or savepoint before the first chunk, retain every required operation's outcome, close valid resources and roll back the owned unit after failure. Do not roll back unrelated pooled work. Validate complete expected bytes and metadata before accepting the result: structural integrity can coexist with an incomplete but valid application object. This is an engineering inference from the controls, not a complete upload protocol.
Download the offline reproduction package, all 40 observations and generated table, source receipts and method and limitations. The package retains raw ordered calls, exact engine identities, closed images and executable checks.
Recorded 15 November 2026 on one host with two existing binaries. Ordered native C-API controls, not concurrent writers, a crash test, a new SQLite defect or a failure-rate estimate. The older distribution build has an alt1 source ID; inspected upstream source is explanatory, not asserted to be byte-identical.
A failed replay can still be committed
Three further controls add a UNIQUE constraint to the stored generated column. The original callback returns x; its incompatible replacement returns Python (x - 1) // 2. Inputs 1 and 2 now both generate 0. Replaying the recorded SQL stops at its second INSERT with SQLITE_CONSTRAINT_UNIQUE (2067), but that exception alone does not discard the preceding INSERT.
| Callback / final action | Replay | IDs before final action | IDs after reopen |
|---|---|---|---|
| Original / complete | Complete | 1, 2, 3 | 1, 2, 3 |
| Changed / rollback | UNIQUE error | 1 | No table |
| Changed / commit (unsafe) | UNIQUE error | 1 | 1 |
In both failed cases, the connection still held an active transaction and row 1 was visible there. Explicit rollback removed the new table and its row. Deliberately committing after the exception instead made that one-row partial restore survive closing and reopening; row 3 was never attempted. A sentinel table committed before replay remained unchanged in every case.
This follows SQLite's default UNIQUE conflict behavior: ABORT reverses the failing statement while retaining earlier statements in the active transaction. It is distinct from the ROLLBACK conflict algorithm. [12] The measured Python executescript() call stopped on the exception; it did not run the trailing COMMIT in the dump. Python transaction settings and the SQL's own boundaries matter, so this result is not a claim about every import program. [10]
The reopened one-row database still passed integrity_check. Structural consistency cannot establish that an import is complete. Reject the failed restore, explicitly resolve its transaction, preserve the source, and validate expected rows and application meaning before publishing a replacement database. Do not commit a failed replay simply because the remaining database passes a check.
Standalone replay harness and complete transaction observations include the actual SQL, errors, pending and reopened rows, source hash and runtime identity.
python3 constraints.py --work-root . --output replay-results.jsonRecorded 2026-10-18 on Python 3.12.3. These are closed-file recovery controls with deliberately incompatible application code, not crash tests or a SQLite defect report.
Why postings are not the original documents
An inverted index maps extracted keys to postings identifying records. One document can appear under several terms. PostgreSQL GIN generalizes this mapping beyond text; its operator class decides which keys and query rules apply. The mapping does not dictate one physical layout: GIN uses a B-tree over keys and posting lists or posting trees for row identities. [GIN structure]
SQLite FTS5 adds column and token positions with detail=full; reduced-detail modes omit information and restrict phrase and NEAR queries. These search structures are not a byte-preserving document copy. With external content, document values come from a separate table or view whose relationship to the postings must be maintained. [13, sections 4.4, 4.6 and 9.2]
Keep representation limits separate from stale maintenance. A query may require a row recheck even when postings are current: PostgreSQL text-search GIN omits weight labels, so weight-sensitive queries need table-row checks. The SQLite experiments below instead test disagreement between indexed terms and their external rows. Neither successful lookup nor internal structure checking alone establishes historical document fidelity. [Query rechecking] [Text-preservation controls]
Four documents, three levels of detail
Zobel and Moffat distinguish bag-of-words retrieval from phrase matching in their 2006 survey. A conjunction of words does not by itself establish their order. The survey separates re-reading candidate documents, retaining positions and indexing phrases. FTS5's restrictions are therefore not a proof that all non-positional indexes make phrase search impossible. The following SQLite observation is not a reproduction of the survey's performance results. [Text-indexing survey, sections 2 and 4]
Each in-memory table contains four constructed documents: row 1 has title red blue; row 2 has blue red; row 3 has title red and body blue; row 4 has only title red. All other bodies are empty. Only the FTS5 detail setting changes; all use unicode61.
| Detail | red AND blue | "red blue" | NEAR(red blue, 0) | title:blue |
|---|---|---|---|---|
full | 1, 2, 3 | 1 | 1, 2 | 1, 2 |
column | 1, 2, 3 | Unsupported (error) | Unsupported (error) | 1, 2 |
none | 1, 2, 3 | Unsupported (error) | Unsupported (error) | Unsupported (error) |
Conjunction finds rows 1, 2 and 3 in every mode, including the split-column document. Full detail distinguishes the ordered phrase from the unordered NEAR match. Reduced detail rejects the unsupported phrase and NEAR requests explicitly; detail=none also rejects the column filter. An error is not a successful search with zero matches. Internal FTS5 integrity checks pass in all three modes: omitted query information is not damaged index structure. [FTS5 detail option]
Standalone probe, negative-control tests and complete observations include the fixture, SQL query strings, errors, SQLite source ID and script hash. Run python3 probe.py --verify results.json with an FTS5-enabled Python SQLite build.
Recorded 2026-11-18 with Python 3.12.3. Constructed in-memory query cases, not a benchmark, crash test, external-content test or replication of the survey.
FTS5 can pass internal checks while searching stale content
Eight further observations test a different dependency: synchronization between a full-text index and its external document table. No callback changes are involved. In five deliberately inconsistent states, both PRAGMA checks and the default FTS5 check succeeded, but at least one search returned the wrong answer. The external-content check rejected all five.
The fixture starts with documents 1 = alpha and 2 = beta, then creates an external-content FTS5 table and insert, update and delete triggers. A plain read of the virtual table returns both documents; MATCH finds neither. Inserting document 3 = gamma indexes that new row but leaves the first two absent. An explicit FTS5 rebuild restores all three. Subsequent trigger-maintained update and delete operations remain consistent.
| State | Wrong queries | External check |
|---|---|---|
| No initial backfill | alpha, beta | Mismatch (267) |
| Insert after triggers | alpha, beta | Mismatch (267) |
| FTS5 rebuild | None | Pass |
| Maintained update/delete | None | Pass |
| Missed update | delta, epsilon | Mismatch (267) |
| REINDEX | delta, epsilon | Mismatch (267) |
| Completed backup | delta, epsilon | Mismatch (267) |
| Rebuild backup | None | Pass |
Next, we deliberately remove the update trigger and change document 1 from delta to epsilon. Searching delta returns row 1 with the current body epsilon; searching epsilon returns nothing. Checking only the displayed body or the total row count would miss this disagreement. The recorded results include complete rows for every query, checked against explicit expectations for these one-token documents.
Ask which relationship the check validates
The FTS5 integrity check distinguishes internal consistency from agreement with external content. The latter requires rank=1; a detected discrepancy raises SQLITE_CORRUPT_VTAB. [13] These commands target the fixture's table named search:
INSERT INTO search(search) VALUES('integrity-check');
INSERT INTO search(search, rank) VALUES('integrity-check', 1);The version-3.45.1 upstream implementation also explains the PRAGMA result: its FTS5 integrity callback invokes the storage check with argument zero. External-content comparison is conditional on the extra flag. It is therefore inaccurate to say that the PRAGMA never checks FTS5 structures; the missing relationship here is index-to-external-content agreement. [14] [15] The measured distribution build's full source identifier is preserved in the JSON; upstream versioned source is explanatory evidence, not a claim of a byte-identical local build.
A completed backup preserves the inconsistency
Bare REINDEX did not repair this fixture. The backup API then completed with SQLITE_DONE, zero pages remaining, and six pages total. After closing and reopening the destination, it returned the same stale search results and the same external-content error. The backup worked as a copy; it was not an application-level repair. [9]
On that disposable destination, INSERT INTO search(search) VALUES('rebuild') restored all five expected query answers and the external check passed. The source hash stayed unchanged throughout backup and destination repair. This does not repair the missing update trigger: future writes still need correct maintenance. Preserve the original, establish which content is authoritative, and test both update handling and known-answer searches before accepting a restored search service.
Reproduce with the standalone harness, regression tests and complete observations. The harness creates private temporary databases, records SQL and runtime identity, and refuses an existing output file. Diagnostic statements run inside rolled-back savepoints; each observation verifies unchanged file hashes.
python3 observe.py --output fts5-results.json
python3 -m unittest -v test_observeRecorded 2026-10-18 using Python 3.12.3. Closed/reopened DELETE-journal fixtures, default tokenizer, no concurrent writer or power interruption. The omissions are deliberate, not evidence of hardware corruption or a new SQLite defect. These five failing states are designed controls, not a measured failure rate.
When different text produces the same index
The previous experiment detected stale tokens. A different boundary appears when a document changes but its indexed representation does not. In five designed one-row fixtures, removing the minus from balance -5 USD or the accent from café stock changed the UTF-8 text while preserving the exact observed token instances. The external rank=1 check accepted both changes. The token-change and token-position controls were rejected with code 267.[Native observations]
| Original / current text | External check | Original UTF-8 retained |
|---|---|---|
balance -5 USDbalance -5 USD | Pass | Yes |
balance -5 USDbalance 5 USD | Pass | No |
café stockcafe stock | Pass | No |
balance -5 USDbalance -7 USD | Mismatch (267) | No |
alpha betabeta alpha | Mismatch (267) | No |
Each independent fixture uses external content with unicode61,detail=full, columnsize=1 and no maintenance triggers. The document is deliberately edited after building its index. This is an in-memory software experiment, not an observation of physical corruption or a SQLite defect. The default tokenizer treats punctuation as separators and removes many Latin diacritics. [Tokenizer contract]
The pinned storage-check callback ignores token start and end byte offsets while incorporating token positions in this detail mode. More fundamentally, the measured original and edited texts have identical token instances, not merely equal hashes. A representation that discards a distinction cannot certify its historical preservation. This inference does not establish detection of every other mismatch.[Explanatory source]
Different tokens can also pass the check
Token equivalence is not the only boundary. In a separate, deliberately stale one-row external-content fixture, changing az to bq passed the external rank=1 check on both measured SQLite 3.45.1 and 3.53.1 builds. The stored token remained az; fresh tokenization produced bq. Searching az returned the current bq document, while searching bq returned nothing.[Native controls]
The pinned entry-checksum code repeatedly multiplies by nine and adds a component. For the same row, column, position and main-index prefix,9*97 + 122 = 9*98 + 113 = 995: the ASCII terms az and bq both yield entry checksum 63932. The noncolliding br control yields 63933 and was rejected with SQLITE_CORRUPT_VTAB. Both builds accepted the unchanged control. Compiling the exact upstream checksum function independently confirmed these arithmetic values. [Pinned source]
All three completed backups retained the measured rows, tokens and check outcomes. Rebuilding the disposable destination restored searches for current content; it did not recover historical text. A passing diagnostic is therefore not proof of exact token agreement. Preserve the original, maintain the index, and test required query answers; where exact agreement matters, compare token instances with fresh tokenization under the same schema in an isolated, consistent snapshot.
This is a constructed checksum collision, not a broken cryptographic hash, an incident rate, a hardware fault or a claim of first discovery. The fixtures use unicode61, detail=full,columnsize=1, no triggers and no prefix indexes. The method,generated comparison and standalone code, sources and observations retain full build identities and the control outcomes. Independent review is still required; this does not certify other schemas or versions.
Keep the historical reference outside the suspect representation
All five completed backups retained the measured current rows and index state. Rebuilding the destination made the two rejecting controls pass while retaining the changed text. It resolved that index disagreement, not the loss of historical content. No reconstruction of earlier text or physical erasure was measured.[Complete results]
Preserve the received artifact before intervention. On a disposable completed copy, record rows, token instances and diagnostics; compare exact bytes or the required application values with a trusted, appropriately dated reference. Rebuild only after deciding which content is authoritative, and keep the before/after evidence. A fresh hash of already changed content is not that historical reference.
Use the method and replay guide,generated table data,standalone code and evidence and technical brief. The retained cross-version comparison preserves diagnostic wording and trace differences; the old strict replay test can fail on another runtime even when scientific outcomes agree. No independent peer review or general version-equivalence claim is made.
Maintenance can preserve text but change document identity
A healthy external-content FTS5 index can lose its document mapping without missing write-maintenance triggers or changed document text. Across nine control cases on each of SQLite 3.45.1 and 3.53.1, renumbering occurred only for ordinary VACUUM on the implicit-rowid table without an ordinary index. IDs 1/3/8 became 1/2/3: MATCH 'charlie' then returned row 3 with body hotel.
PRAGMA integrity_check, quick_check and the internal FTS5 check passed in every case. The explicit external-content check, INSERT INTO ft(ft,rank) VALUES('integrity-check',1), rejected the changed mapping with SQLITE_CORRUPT_VTAB (267). Here that check detects the mismatch; the earlier token-equivalence and checksum controls explain why a pass is not a historical-preservation certificate. [FTS5 contract]
| Schema / operation | IDs for alpha / charlie / hotel | Body for MATCH charlie | External check |
|---|---|---|---|
| Implicit rowid; no ordinary index VACUUM | 1 / 2 / 3 | hotel | Rejects 267 |
| Implicit rowid; no ordinary index VACUUM INTO | 1 / 3 / 8 | charlie | Pass |
| Implicit rowid; no ordinary index Backup API | 1 / 3 / 8 | charlie | Pass |
| Implicit rowid; body index VACUUM | 1 / 3 / 8 | charlie | Pass |
| Implicit rowid; body index VACUUM INTO | 1 / 3 / 8 | charlie | Pass |
| Implicit rowid; body index Backup API | 1 / 3 / 8 | charlie | Pass |
| id INTEGER PRIMARY KEY VACUUM | 1 / 3 / 8 | charlie | Pass |
| id INTEGER PRIMARY KEY VACUUM INTO | 1 / 3 / 8 | charlie | Pass |
| id INTEGER PRIMARY KEY Backup API | 1 / 3 / 8 | charlie | Pass |
VACUUM INTO and completed backup API copies preserved the mapping in these fixtures, as did an ordinary body index and id INTEGER PRIMARY KEY. SQLite documents that unaliased rowids can change under VACUUM. In the pinned 3.45.1 transfer code, generating new rowids requires both no ordinary destination index and no VacuumInto flag. This explains the controls; an incidental index is not a durable identity contract. The 3.53.1 result is an observation, not a source audit of that implementation. [VACUUM] [transfer code]
All three write-maintenance triggers were exercised before the operation. Their audit log did not grow during VACUUM. The pinned implementation copies trigger and virtual-table definitions after ordinary table contents; surviving trigger names alone do not certify a preserved relation between postings and documents. [maintenance order]
Rebuilding FTS on a disposable copy restored searches against current content but retained the new IDs. Preserve the original mapping before maintenance, use a true rowid alias where persistent identity is required, and test full ID/body answers. INT PRIMARY KEY is not equivalent to INTEGER PRIMARY KEY; the inline INTEGER PRIMARY KEY DESC exception also matters. Only the simple declaration was measured here. [rowid contract] [key declaration]
Download the standalone evidence and replay package, generated table and hashes, or method and limitations. The check definition separates consistency from preservation.
Closed DELETE-journal fixtures, unicode61, detail=full, no concurrent writer, crash or performance measurement. Captures retain source IDs, complete queries and the one differing diagnostic message. Two builds were run by the same research agent; independent source/prose review is not independent native replication. No incident rate or newly discovered engine defect is claimed.
A repaired index is not a recovered history
Three different mechanisms lead to the same recovery question. Token normalization can hide changed text; a checksum collision can hide unequal token instances; maintenance can change document identifiers. Hesela reuses the 17 designed cases above to compare two separate requirements: the original ID-to-text mapping and every stored term/document/column/position tuple against a fresh index of the current rows. [Vocabulary API] [Replay evidence]
| Witness | Checks | Current index | Historical mapping |
|---|---|---|---|
| Unchanged baseline | Pass | Equal | Equal |
| Minus sign removed | Pass | Equal | Different |
| az replaced by bq | Pass | Different | Different |
| VACUUM followed by rebuild | Pass | Equal | Different |
Of 59 dependent states per build, 13 passed all three checks while failing at least one comparison. In 7 rebuilt states, the index matched current text but the original ID-to-text mapping was lost. These counts describe deliberately selected counterexamples, not failure rates or independent incidents.
Keep the historical baseline separate from the repair target. Rebuilding can restore current search consistency without recovering a lost minus sign or an earlier document ID. A manifest created after damage cannot establish the earlier state. A recovery workflow needs a trustworthy earlier snapshot, stable document keys and a separately protected record of what must survive.
The demonstrator directly compares rows and token instances, not just their hashes. It supports these fixed TEXT-only, unicode61, detail=full fixtures and constructs the reference index using the same SQLite engine. It does not provide independent engine validation, historical authenticity, crash testing or a general-purpose production database checker.
The test oracle matters. Rigger and Su's Pivoted Query Synthesis constructs queries that must return a chosen row; it checks that row's presence, not the entire result set or its ordering. Our fixed-fixture comparison checks complete row mappings and token tuples, but its fresh index shares the engine under test. Neither technique alone establishes every aspect of recovery correctness. This is a methodological comparison, not a reproduction of PQS. [OSDI 2020, sections 2 and 3]
Download the standalone replay package, derived table and source hashes, and method and limitations. The captures retain all 59 comparisons, including successful controls.
Search absence is not an erasure result
A deleted document can disappear from MATCH while its token remains in the stored index. FTS5 secure-delete removes old index entries; core secure_delete controls zeroing of deleted ordinary-table content. These are separate settings.[FTS5 contract] [Core limits]
Hesela tested all four OFF/ON combinations on fresh, internal-content FTS5 databases with three single-token documents and automerge disabled. After deleting the middle document, closing and reopening, every MATCH query omitted it and both survivors remained. PRAGMA integrity checks and the FTS5 diagnostic passed in every case. Unlike the external-content fixtures above, these use FTS5's own content table without maintenance triggers.
| Core / FTS5 | Deleted MATCH rows | Shadow blobs with token | File token occurrences |
|---|---|---|---|
| OFF / OFF | 0 | 2 | 3 |
| OFF / ON | 0 | 0 | 1 |
| ON / OFF | 0 | 2 | 2 |
| ON / ON | 0 | 0 | 0 |
A shadow-blob count is not a count of recoverable documents. FTS5's normal deletion path writes delete-keys; the same token can occur in an older posting and its deletion marker. This byte scan does not reconstruct either as a complete record.[Index deletion mechanism]
Core-only zeroing left the token in current shadow blobs. FTS5-only deletion removed it there but left a match in the main file. With both enabled, neither scan found this token. A positive match establishes residue; a negative scan does not prove complete forensic erasure. The recorded SQLite 3.45.1 build is not a current-version or patch recommendation.
Settings were applied before deletion. FTS5 secure-delete can also affect compatibility with engines older than 3.42.0; older-reader behavior was not tested here.[Compatibility warning]
Inspect the generated observations,method and limitations and standalone code/data archive. Two retained runs contain 42 raw files across the FTS5 and WAL fixtures, SQL traces and library identities. A separate verifier checks bytes, persistent settings and diagnostics on disposable copies. This is repeatability, not independent peer review.
Deletion also has a history boundary. Continue with WAL checkpoint completion versus history erasure: clean current pages do not establish clean old logs or backups. No physical media, filesystem snapshot, crash or general record-recovery test was performed.
All triggers can exist and REPLACE can still leave stale search results
A second FTS5 experiment keeps all three maintenance triggers and backfills the index before writing. It varies only the base-table statement and an explicitly set recursive_triggers value. Each independent fixture starts with two documents, changes document 1 from alpha to delta, and checks complete search rows after closing and reopening.
| Base-table write | Recursive triggers | Events recorded | Old-token search | External check |
|---|---|---|---|---|
| REPLACE | Off | insert | Row 1: delta | Mismatch (267) |
| REPLACE | On | delete, insert | No row | Pass |
| UPSERT | Off | update | No row | Pass |
| UPSERT | On | update | No row | Pass |
With recursive triggers off, INSERT OR REPLACE succeeded but recorded only an insert event. Searching the old token alpha still returned row 1 displaying delta. The new-token query also found delta. Counting documents or testing only the new word would therefore miss the stale posting. The external-content check rejected it with code 267.
For a primary-key conflict, SQLite documents REPLACE as deleting the conflicting row before inserting the replacement; its delete triggers run only when recursive triggers are enabled. [12] With that setting on, the fixture recorded delete then insert and removed the old posting. The tested UPSERT used ON CONFLICT(id) DO UPDATE SET body=excluded.body; it recorded an update and passed both query and external-content checks under either setting. [16]
These are writes to the ordinary docs table, not REPLACE or UPSERT applied directly to the FTS5 virtual table. Do not transfer these results to all conflict targets, trigger designs or virtual-table operations. Explicitly verify connection settings and actual write paths; globally enabling recursive triggers can change other trigger behavior.
Rollback is a separate control
Before committing each case, the harness executed the same statement in an explicit transaction and rolled it back. After reopening, all original rows and five query answers were restored; audit events were absent and the closed-file SHA-256 matched the baseline. The subsequent committed operation then produced the table above. This checks rollback in these fixtures, not power-loss durability.
Gaffney and colleagues describe SQLite's execution, storage and transaction layers in their 2022 architecture and performance study. [17] Our inference is narrower: an engine's transaction guarantees do not supply an application's missing index-maintenance invariant. Their benchmarks are not evidence for our FTS5 outcomes, which come from the executable controls here.
Download the REPLACE/UPSERT harness, its required observation helper, regression tests and complete results. Keep both Python modules together. The observations include trigger events, full query rows, SQL, transaction state, source identity and code hashes.
python3 replace_probe.py --output replace-results.json
python3 -m unittest -v test_replace_probeRecorded 2026-10-19 on Python 3.12.3. All maintenance triggers present; one INTEGER PRIMARY KEY conflict; single-token ASCII documents; DELETE journal; no concurrent writer. This demonstrates documented behavior, not a newly discovered SQLite defect.
The parent can return while its children disappear
Replacing a parent row is not necessarily harmless when its key stays the same. In a new controlled fixture, REPLACE with ON DELETE CASCADE removed both children of parent 1, then inserted parent 1 again. After commit and reopen, integrity_check returned ok and foreign_key_check returned no violations. The deletion obeyed the schema; a check cannot recover an unstated requirement to keep those children.
The fixture contains two parents and three children: IDs 11 and 12 belong to parent 1; ID 21 belongs to an untouched sentinel parent 2. The tested UPSERT changes only the label through ON CONFLICT(id) DO UPDATE SET label=excluded.label. Every foreign key is declared DEFERRABLE INITIALLY DEFERRED; the main matrix keeps defer_foreign_keys=0.
| Write / delete action | Outcome | Child IDs after reopen |
|---|---|---|
| REPLACE CASCADE | Committed | 21 |
| UPSERT CASCADE | Committed | 11, 12, 21 |
| REPLACE RESTRICT | Statement rejected; rolled back | 11, 12, 21 |
| UPSERT RESTRICT | Committed | 11, 12, 21 |
| REPLACE NO ACTION | Committed | 11, 12, 21 |
| UPSERT NO ACTION | Committed | 11, 12, 21 |
A missing parent-delete event does not stop the cascade
With recursive triggers off, the cascade trial logged child deletions 11 and 12 and a parent insert, but no parent-delete event. Turning recursive triggers on added that event without preserving either child. SQLite documents separate rules for REPLACE delete triggers and foreign-key actions. [12] [18] Versioned deletion code dispatches foreign-key actions before AFTER DELETE triggers. That source explains the observed sequence; it is not proof of a byte-identical distribution build. [20]
Schema deferral and global deferral are different controls
In the main matrix, RESTRICT rejected REPLACE during the statement, even with the deferred schema declaration. The transaction remained open, and the harness explicitly rolled it back. NO ACTION allowed the same-key replacement to commit. This matches the documented immediate RESTRICT action under schema-level deferral. [18]
Do not extend that rule to every setting. Four extra controls enabled PRAGMA defer_foreign_keys=ON inside the transaction. On the measured build, the RESTRICT replacement then committed and retained all three children under both journals and trigger settings. The pinned fkActionTrigger() implementation skips the RESTRICT action program when SQLITE_DeferFKs is set. [19] This is a version-scoped distinction, not advice to disable a restriction an application depends on.
Check preservation as well as referential validity
Two additional controls deliberately deleted the parent with foreign-key enforcement off, then reopened with enforcement on. Both retained orphan IDs 11 and 12; foreign_key_check reported each one while integrity_check still passed. Its documented scope excludes foreign-key violations. [21] The clean cascade result and these rejected orphan results answer different questions: valid remaining references do not prove preserved data.
Our engineering conclusion is to inspect the actual conflict target, delete action, trigger settings and expected dependent rows before treating replacement as update. The tested label-only UPSERT retained the children, but other assignments or triggers can change its effects. Do not switch off foreign keys to make an import succeed.
The standalone harness, known-answer tests and complete observations retain schema, SQL, trace, errors, complete rows, runtime identity and code hash. Each of the 28 write cases also ran a rollback trial that restored the original rows after reopening. No existing database path is accepted.
python3 -B observe.py --output my-results.json
python3 -B -m unittest -v test_observeRecorded 2026-10-21 on Python 3.12.3. Single writer, one INTEGER PRIMARY KEY conflict, two journal modes. These are controlled software observations, not a crash test, hardware finding or estimate of incident frequency.
Parent-key integrity depends on the index lifetime
An index can support a relationship's validity, not just accelerate reads. In these controlled fixtures, removing an external UNIQUE index and then its parent table committed with foreign_keys=1. The child remained; integrity_check returned ok; a completed Online Backup API copy preserved the orphan. This reproduces SQLite's documented exception, not a newly discovered defect. [Parent-key rules]
The experiment ran 8 scenarios in DELETE and WAL source journal modes on SQLite 3.45.1 and 3.54.1: 32 case executions and 64 retained source/backup images. Each fixture began with one parent and one non-NULL child reference, immediate NO ACTION and no user triggers. These are designed cases, not a population failure rate.
| Scenario | End decision | Before-end FK check | Reopened copy FK check |
|---|---|---|---|
| external-baseline | commit | No violations | No violations |
| external-drop-index | commit | SQLITE_ERROR (mismatch) | SQLITE_ERROR (mismatch) |
| external-drop-both | commit | 1 violation | 1 violation |
| external-drop-parent | rollback-statement-error | No violations | No violations |
| inline-drop-parent | rollback-statement-error | No violations | No violations |
| external-rebuild-index | commit | No violations | No violations |
| guard-drop-index | rollback-guard | SQLITE_ERROR (mismatch) | No violations |
| guard-drop-both | rollback-guard | 1 violation | No violations |
Removing only the index left both rows intact but made foreign_key_check fail with SQLITE_ERROR and a mismatch diagnostic. Removing the parent table too produced a completed check with one violation. An errored check is not zero violations. Direct parent removal with the supporting index still present, or with inline UNIQUE, was rejected; the harness then explicitly rolled back. [Check scope]
The guarded cases checked the final candidate before COMMIT, rejected both checker errors and violation rows, and explicitly rolled back to the original schema and rows. Their reopened backups are healthy because rollback happened first. Dropping and rebuilding the index within the transaction passed the final check, despite an intermediate mismatch. This is a fixture-level guard, not a general migration library; a check after an autocommitted change cannot undo it. [Transaction boundary]
SQLite recommends defining parent uniqueness within the table declaration. In the pinned 3.45.1 implementation, sqlite3FkDropTable compiles its implicit delete with triggers disabled, and sqlite3FkLocateIndex suppresses the mismatch diagnostic in that context. This explains the documented path, not every DROP operation. [Pinned implementation]
The recovery implication is that a faithful copy preserves relational defects as well as valid rows. Accept a restored relationship only after the relevant check completes successfully with no violations, then verify the intended application state. As the earlier recovery experiment shows, a reference to the wrong existing parent can still pass.
Inspect the machine-readable results, source receipts and offline replay package. The package retains the SQL, full observations, engine identities, known-answer tests and all 64 images. The two raw captures are SQLite 3.45.1 and SQLite 3.54.1.
python3 -B -m unittest discover -s . -v
python3 -B verify.py evidence/sqlite-3.45.1/observations.json
python3 -B verify.py evidence/sqlite-3.54.1/observations.jsonRun from the extracted package with Python 3.11+ and SQLite support. Captured 11 November 2026; full matrix through Python's sqlite3 wrapper, plus one separate 3.45.1 CLI confirmation. No crash, concurrent writer, deferred constraint, CASCADE action, attached database or general migration framework was tested. Journal modes do not constitute a power-loss test.
MATCH FULL can preserve an incomplete reference
A completed backup preserved three partially specified composite references in these SQLite controls, while integrity_check returned ok and foreign_key_check returned no rows. The schema contained MATCH FULL; adding STRICT did not change the outcome. The copy preserved the database correctly, but that database did not meet an all-or-none reference requirement.
SQLite documents that it parses MATCH clauses without enforcing their selected mode. Any NULL child-key component exempts the row from a parent lookup. The version-3.45.1 implementation shows this explicitly: fkLookupParent emits a NULL branch for each component before searching for a parent. This source explains the mechanism; it does not establish byte-identical provenance for the distribution library. [MATCH rules] [Versioned implementation]
The retained snapshots expose another inspection trap: the final MATCH field of PRAGMA foreign_key_list(child) was NONE in all five policies on both builds, while the stored DDL retained MATCH FULL where declared. That field did not distinguish the nullness guards, and NONE did not mean enforcement was disabled. Inspect the actual constraints and test incomplete references; neither declaration text nor that field alone establishes the application contract. [SQLite 3.45.1 snapshots] [SQLite 3.54.1 snapshots]
Same inputs, five constraint policies
Each schema received nine ordered INSERT/UPDATE attempts on SQLite 3.45.1 and 3.54.1. The 90 attempts are controlled observations, not independent incidents. The 24 retained images include closed sources, completed backups and deliberate orphan controls.
| Schema policy | Accepted | Partial rows |
|---|---|---|
| Default match mode | 7 / 9 | 3 |
| MATCH FULL | 7 / 9 | 3 |
| STRICT + MATCH FULL | 7 / 9 | 3 |
| All-or-none CHECK | 3 / 9 | 0 |
| Both columns NOT NULL | 2 / 9 | 0 |
The unguarded variants retained (7,NULL), (99,NULL) and (NULL,11). The parent keys were (7,11) and (8,12), so even the non-NULL prefix 99 had no parent. STRICT typing did not make these ordinary columns nonnullable. [STRICT tables]
Enforcement was active: every schema rejected a fully specified missing parent on both INSERT and UPDATE. A separate complete orphan, deliberately inserted with enforcement disabled, was reported after enforcement was reenabled and after backup. Each copy reached SQLITE_DONE; reopened source and destination had equal complete typed states, schema and diagnostics. File hashes identify the retained artifacts, not a universal byte-identity guarantee. [Backup completion]
Specify completeness separately
For an optional two-column reference, the tested guard was:
CHECK ((a IS NULL) = (b IS NULL))It admits two absent or two present components and rejects either mixed case. The foreign key still checks whether the fully specified parent exists. These IS NULL predicates yield definite booleans; a CHECK expression that instead evaluates to NULL is accepted by SQLite. If absence is forbidden, both columns need NOT NULL as well as the foreign key. [Constraint rules]
For existing rows, this separate audit finds incomplete references:
SELECT id FROM child
WHERE (a IS NULL) <> (b IS NULL)
ORDER BY id;PostgreSQL 18 documents mixed NULL/non-NULL rejection under MATCH FULL. PostgreSQL was not executed in this study. The immediate CHECK above is not a complete replacement for deferred MATCH FULL or a test of every referential action. [PostgreSQL contract]
Combine the completeness audit with a successfully completed foreign-key check and the application's expected relationships. The parent-key lifetime controls test whether the supporting key exists; this section tests whether the child reference must be complete. Both are separate from backup completion.
Download the offline code, tests and database images, run instructions, generated comparison, claim-to-source map and SHA-256 manifest.
python3 -B verify.py evidence/sqlite-system evidence/sqlite-provider
python3 -B -m unittest -v test_match_fullConstructed controls captured 18 November 2026. Single writer, DELETE journal, integer keys and immediate NO ACTION constraints; no crash, concurrency, performance or field-frequency measurement. This reproduces documented semantics, not a newly discovered SQLite defect.
One incoming row can displace two parents
A second unique key changes the scope of replacement. Our next fixture has parent rows (1, alpha), (2, beta) and an untouched (3, gamma). Each has one child. The incoming row (1, beta, new) collides with parent 1 through its primary key and parent 2 through its unique code.
REPLACE deleted both conflicting parents and cascaded to child IDs 11 and 21. Only sentinel child 31 survived; the new parent 1 carried code beta. With recursive triggers enabled, the audit recorded both parent deletions. With them disabled, those two audit events were absent, but the child deletions still occurred. The final database passed both integrity checks.
| Incoming (1, beta, new) | Outcome | Remaining parent IDs | Remaining child IDs |
|---|---|---|---|
| REPLACE | Committed | 1, 3 | 31 |
| UPSERT: label only | Committed | 1, 2, 3 | 11, 21, 31 |
| UPSERT: code and label | UNIQUE error; explicitly rolled back | 1, 2, 3 | 11, 21, 31 |
The label-only UPSERT explicitly targets ON CONFLICT(id). It updates parent 1 while retaining its original code alpha, so it does not attempt the conflicting code change. Adding code=excluded.code instead raises SQLITE_CONSTRAINT_UNIQUE (2067). In that trial the statement's rows and audit events were unchanged, the transaction remained open, and our harness rolled it back. SQLite documents ABORT semantics for a constraint violation inside DO UPDATE. [16]
Choose the conflict target and assignments from the application's identity rules. A label-only update may preserve children while failing a requirement to change the code; it is not a universal substitute for replacement. Inspect all unique constraints when deciding which existing records a write may remove.
Why the expected rows are explicit
Rigger and Su's OSDI 2020 paper builds a query oracle around a row that must appear. Its discussion explicitly limits that containment check: it does not generally validate insertion or deletion, result cardinality, or transaction behavior. [7] Here the test instead compares complete parent and child rows, audit-event sets and rollback results against hand-authored expectations. This is a small write-semantics fixture, not a reproduction of SQLancer or a newly found engine bug.
Download the two-conflict harness beside its required observation helper, the six known-answer tests and the complete 12-fixture record. The original 30-case record above remains unchanged.
python3 -B multi_unique.py --output my-multi-results.json
python3 -B -m unittest -v test_multi_uniqueRecorded 2026-10-21 on Python 3.12.3. One INTEGER PRIMARY KEY plus one BINARY-collated TEXT UNIQUE key; ON DELETE CASCADE; schema deferral enabled, global deferral off. Single writer, no crash injection or performance measurement. Event order is recorded but not promised.
Reproduce and inspect the evidence
The standalone Python harness uses the standard library, creates private temporary fixtures and refuses an existing output file. It accepts a working directory, never a production database path. The complete observations include SQL, query plans, full rows, diagnostics, hashes, compile options and SQLite source identity.
python3 observe.py --work-root . --output my-results.jsonEight primary observations cover two index kinds and four runtime states. One additional fixture tests a UNIQUE collision. These are designed cases, not sampled incidents, so no failure-rate estimate or sampling interval applies. The result was recorded on 2026-10-18 with Python 3.12.3 and SQLite 3.45.1.
Copies came from closed DELETE-journal fixtures. In those primary runtime-copy cases, no backup API, concurrent writer, live-file copying, WAL, power interruption, ICU upgrade or cross-platform transfer was tested. The forced plans isolate semantics; this is not a benchmark or a prediction of which plan a production query will choose. Rebuilt indexes were checked under the selected callback, not certified against an entire application's requirements.
Primary sources
For changes that happen before storage, see the numeric import experiment: exact identifiers, STRICT coercion and what a completed backup preserves.
- SQLite C API: Define New Collating Sequences
- SQLite: Deterministic SQL Functions, sections 2 and 4
- SQLite: Indexes On Expressions, restrictions
- SQLite: Stale Expression Indexes, platform variation and version-scoped recovery
- SQLite PRAGMA quick_check: omitted checks
- SQLite REINDEX: rebuild scope and name resolution
- Manuel Rigger and Zhendong Su: Testing Database Engines via Pivoted Query Synthesis, OSDI 2020, sections 2, 3 and 6, pp. 667-682
- SQLite: Generated Columns, STORED versus VIRTUAL, index types and limitations
- SQLite Backup API: copying database content
- Python 3.12 sqlite3: iterdump and backup
- SQLite PRAGMA table_xinfo: generated-column flags
- SQLite: ON CONFLICT, default ABORT versus transaction ROLLBACK
- SQLite FTS5: external-content tables, pitfalls, integrity-check and rebuild
- SQLite version-3.45.1: FTS5 integrity callback and special-command dispatch
- SQLite version-3.45.1: storage integrity and external-content comparison
- SQLite UPSERT: conflict-targeted DO UPDATE and virtual-table limitations
- Gaffney et al.: SQLite: Past, Present, and Future, PVLDB 15(12), 3535-3547 (2022), sections 2 and 4; DOI 10.14778/3554821.3554842
- SQLite Foreign Key Support: actions, schema-level deferral and recursive-triggers boundary
- SQLite version-3.45.1 fkey.c: RESTRICT deferral branch and action programs
- SQLite version-3.45.1 delete.c: foreign-key actions before AFTER DELETE triggers
- SQLite PRAGMA: integrity_check, foreign_key_check and defer_foreign_keys
- SQLite maintainer: generated-table BLOB rejection, 28 August 2024
- SQLite 3.54.1: generated-table gate in sqlite3_blob_open
- SQLite 3.45.1: raw-record transfer optimization
- SQLite 3.54.1: raw-record transfer optimization
- SQLite 3.54.1: VACUUM schema and content transfer
- SQLite: VACUUM INTO logical-copy contract
- SQLite 3.54.1: displayP4 formats function name and argument count
- SQLite RTree module: coordinate types, roundoff and integrity checking
- SQLite 3.45.1 RTree source: rtreeValueDown and rtreeValueUp
- SQLite numerical storage and the RTree representation exception
- Hesela: RTree time-precision evidence and reproduction package
- SQLite FTS5: secure-delete setting and older-reader compatibility
- SQLite: PRAGMA secure_delete and virtual-table limitations
- Hesela: SQLite deletion scope, generated observations and provenance
- SQLite FTS5: Unicode61 tokenizer, separator and diacritic defaults
- Hesela: FTS5 token-equivalence captures and explicit cross-runtime comparison
- SQLite 3.45.1: commit-pinned FTS5 tokenization callback and storage integrity check
- SQLite 3.53.1 pinned entry-checksum implementation
- Hesela: three checksum controls on two SQLite builds
- SQLite: VACUUM and unaliased rowid changes
- SQLite: rowid persistence and integer-key aliases
- SQLite: exact INTEGER PRIMARY KEY alias rules
- Hesela: nine maintenance-identity cases on each of two SQLite builds
- SQLite 3.45.1 pinned transfer: rowid and VacuumInto branches
- SQLite 3.45.1 pinned VACUUM: contents before trigger definitions
- Hesela: historical-row and current-index acceptance, 17 designed cases
- SQLite FTS5: instance vocabulary and token positions
- Hesela: legacy generated values, RO/RW checks and exact native replay
- SQLite Foreign Key Support, sections 3 and 5: external UNIQUE-index lifetime
- SQLite: explicit transactions and rollback boundary
- SQLite 3.45.1 pinned fkey.c: sqlite3FkDropTable and sqlite3FkLocateIndex
- SQLite C API: BLOB handles expire on same-row changes
- SQLite C API: failed BLOB writes and earlier completed chunks
- SQLite C API: a failed BLOB reopen aborts the handle
- SQLite C API: closing a BLOB and conditional transaction completion
- SQLite: savepoint rollback and transaction-stack rules
- SQLite pinned vdbeblob.c: statement finalization on expired access (older source)
- SQLite pinned vdbeblob.c: statement finalization on expired access (newer source)
- Gaffney et al.: SQLite: Past, Present, and Future (PVLDB 2022), sections 2.1-2.2
- PostgreSQL 18: GIN key extraction, postings and internal B-trees (sections 65.4.1-65.4.4)
- PostgreSQL 18: text-search GIN weight labels and row rechecking (section 12.9)
- Justin Zobel and Alistair Moffat (2006), Inverted Files for Text Search Engines, ACM Computing Surveys 38(2), article 6, sections 2 and 4. DOI: 10.1145/1132956.1132959
- SQLite: Partial Indexes, predicate membership and planner rules
- SQLite: CREATE INDEX, uniqueness and NULL keys
- PostgreSQL 17: Partial Indexes, implication at planning time
- PostgreSQL 17: PREPARE, generic and custom plans
- SQLite: SQL Language Expressions, Boolean expressions and NULL
- Stonebraker: The Case for Partial Indexes, UCB/ERL M89/17 (1989), sections 3.1-3.4
- SQLite: Query Planning, multicolumn keys and search/sort
- SQLite: Query Optimizer Overview, skip-scan optimization
- SQLite: CREATE INDEX, key expressions and uniqueness
- PostgreSQL 18: Multicolumn Indexes, key versus payload and scan bounds
- PostgreSQL 18: Combining Multiple Indexes, bitmap ordering
- PostgreSQL 18: Unique Indexes, combinations and NULLS NOT DISTINCT
- SQLite: EXPLAIN QUERY PLAN, diagnostic output stability
- Selinger, Astrahan, Chamberlin, Lorie and Price (1979): Access Path Selection in a Relational Database Management System, SIGMOD, pp. 23-34; sections 4-5; DOI 10.1145/582095.582099
- SQLite: composite foreign keys and unsupported MATCH modes
- SQLite version-3.45.1: fkey.c, fkLookupParent NULL-component branch
- SQLite: STRICT-table nullability rules
- SQLite: Online Backup API completion and cleanup
- SQLite: CHECK and NOT NULL constraints
- PostgreSQL 18: composite foreign keys and MATCH FULL
- SQLite Datatypes: BINARY and ASCII-only NOCASE collation
- SQLite SELECT: NULL equality and collation in GROUP BY
- SQLite CREATE TABLE: NOT NULL and UNIQUE constraints