8000 EPIC-05: persistence, schema and migrations by zakariaf · Pull Request #10 · zakariaf/Odova · GitHub
[go: up one dir, main page]

Skip to content

EPIC-05: persistence, schema and migrations - #10

Merged
zakariaf merged 25 commits into
mainfrom
epic/05-persistence-and-migrations
Sep 4, 2026
Merged

zakariaf merged 25 commits into
mainfrom
epic/05-persistence-and-migrations

Conversation

@zakariaf
@zakariaf zakariaf commented Sep 4, 2026
Copy link
Copy Markdown
Owner

What and why

The floor the whole app stands on. Ten SQLite tables where a corrupt row cannot
be written, one write path, one distance history, and a migration that cannot
lose a record — because losing eight years of service history outranks every
feature in this product (SPEC.md §2, CLAUDE.md rule 3), and every way it can
happen is decided here.

The parts worth a reviewer's attention are not the tables. They are the three
places where something compiled, analysed clean, passed a test, and was 8000 wrong.

Closes

EPIC-05 tasks 1–11.

Spec

SPEC.md §3 (Canonical units; Identity, timestamps, deletion; Entities; Enums;
The odometer; Invariants and validation; Durability), §6.3 Versioning and
migration, §6.4.4 The automatic safety copy, §14 Edge cases, §17 Data-safety
gate.

SPEC.md is edited in this PR, deliberately, because it contradicted
itself.
§3's OdometerCorrection.reason enum listed four values including
unit_mixup; §14 Edge cases says in as many words "unit_mixup is removed as
a correction reason". §14 is right and is the narrower, explicitly-decided
statement — storage is canonical metres and the odometer unit is a per-record
fact, so a km cluster fitted to a miles car needs no offset at all: the reading
is entered in the unit the new cluster shows and converted on the way in.

The CHECK ships three reasons and §3 was fixed rather than the CHECK widened.
Widening would have offered the user a resolution that does nothing; leaving §3
alone would have left the next reader to rediscover the contradiction.

Two places the code is deliberately stricter than the epic, both recorded in
epics/progress/EPIC-05.md:

  • The models live in lib/core/domain/models/, not lib/domain/.
    test/policy/structure_test.dart sanctions seven top-level directories and
    core is the one labelled "pure Dart domain — no Flutter, ever". The gate is
    an existing decision from EPIC-01 and it wins over the epic's prose.
  • The Result/Failure spine the epic's Where we are now says already exists
    did not. It is built here, because task 5.2's parse and task 5.7's
    repositories both return one and a second vocabulary would mean converting
    between them forever.

Localisation

No user-visible string in this PR. Every failure carries a stable code and
typed parameters and never a message —
test/policy/typed_failures_test.dart is the gate, and it lists the names that
mean "show this to the user" rather than every name that happens to be a
String. A String message on a failure compiles, reads naturally at the call
site, and produces an English sentence on an Arabic screen; it is invisible
until somebody who does not read English opens the app.

OdometerWouldGoBackwards carries the conflicting reading's cumulative value
AND its date, because SPEC.md §3's three resolutions all need both and the
presentation edge localises from there.

Visual parity

Not applicable — this epic builds no screen. Nothing in it renders. The
epic says so explicitly and carries no parity line in its definition of done.

Tests

2,110 tests green, analyzer clean at --fatal-infos --fatal-warnings, the pure
dart test test/core lane green at 145, every repo gate green locally.

Three things that compiled, analysed clean and were wrong.

.references(Vehicles, #id, onDelete: KeyAction.cascade) generated no
REFERENCES clause at all
. service_items.vehicle_id came out as a bare
TEXT NOT NULL, so an item pointing at a vehicle that does not exist was
accepted and the cascade Undo depends on did not exist. Found by a test that
inserts an orphan; nothing in Dart could have.

.withLength(min: 3, max: 3) is a Dart-side validator on the generated
companion and emits nothing into CREATE TABLE. All four currency columns were
unchecked in the database, and the exponent that turns 4599 into 45.99 comes
from that code.

build.yaml did not exist, so drift_dev make-migrations had been failing with
"No databases found in the build.yaml file" — meaning the entire schema-snapshot
and step-by-step machinery was unavailable. That is a thing you discover on the
day you need to migrate somebody's history, not before.

The first two are now gated by test/data/db/schema_reality_test.dart, which
asks SQLite what it actually has: no withLength in any table file, every
column whose name contains currency carries length(col) = 3 in its SQL, and
every *_id column that names another table appears in
PRAGMA foreign_key_list. The last is derived rather than listed, so a foreign
key added in a later epic is covered without editing the test.

Six tests that passed and proved nothing. Each is listed in the progress
file with what it was replaced by. The one worth reading is the migration test:
it asserted the database file was byte-identical after a failed migration and
passed with the restore deleted — because drift wraps onUpgrade in a
transaction, so a step that throws before committing is rolled back by SQLite.
The snapshot exists for the other case, which is the shape of
AppDatabase.onUpgrade itself: run stepByStep in a transaction, then throw if
PRAGMA foreign_key_check finds orphans, after the commit. The test now has
both, and against the second one removing the restore loses the user's garage
and the app comes up empty and healthy-looking.

What the mutation sweeps pinned. Roughly thirty behaviours were mutated in
turn and watched go red: every pragma, the Crockford alphabet, the ULID's
monotonic increment, the wrong-prefix check, six schema constraints, the
ON DELETE SET NULL that keeps history when a reminder is deleted, six branches
of the monotonicity guard, the index column ORDER (which leaves the index
existing and used while adding a sort — a test that only checked "uses the
index" would have passed), the cascade's WHERE vehicle_id, the undo's
timestamp match, the purge cutoff, the fan-out's lookup key, and all three of
guardPersist's catch arms.

Four defences that could not be made to fail, and the test says so rather
than implying otherwise. Closing the connection checkpoints the WAL into the
main file, which masks the close-before-restore ordering, the delete-before-copy
pass, the checkpoint and the sidecar copies all at once. They stay because each
covers a case the test cannot produce — a checkpoint blocked by a reader, a
process killed between commit and close, a platform where deleting an open file
is not benign — and what is asserted instead is the end state.

Indexes are proven used, not asserted to exist: EXPLAIN QUERY PLAN over
the real queries, including a TEMP B-TREE assertion. The fuel page is keyset,
not OFFSET, asserted on the query text — OFFSET makes page 50 read 2,500
rows and silently skips or repeats a row when something is inserted between two
pages, which for a log people backdate into is not hypothetical.

Zero-record-loss oracle: 12,000 records, row counts AND a content hash
either side. Counts alone would not notice a migration that copied the right
number of rows with the wrong values in them. The oracle has its own test —
changing one cost by a cent must change the hash while the counts agree.

Four new dependencies, audited: drift, sqlite3, sqlite3_flutter_libs and
path_provider reach no socket, and crypto is dev-only.

What the review passes changed

/simplify and /code-review both ran before this PR was opened, and between
them they found one blocking defect and thirteen real bugs. Every finding is
recorded applied-or-answered in epics/progress/EPIC-05.md; these are the ones
a reviewer should know about.

lib/data/failures/ was gitignored. .gitignore's **/failures/, written
for golden diff artefacts, also matched the sealed PersistFailure family that
nine files in the data layer import. It was never committed. git status read
clean, every gate passed locally, and a fresh clone would not have built.
Found because a review agent noticed a file it had been asked to review was not
in git ls-files.

Four of the five write paths into odometer_readings skipped the monotonicity
guard.
checkReading had one call site; the fan-out wrote with a raw upsert.
A fill-up whose odometer went backwards was accepted. EPIC-05 task 5.9 names
this test and it did not exist.

Five ways to lose or corrupt a history, each returning SUCCESS. A
re-parented record stranded its reading on the old vehicle with the new
vehicle's odometer. Clearing an odometer cascade-deleted a correction, taking
187,412 km of offset off every later reading. A failed restore on a full disk
left neither the database nor the snapshot, so the next launch looked like a
fresh install. The safety copy could throw into the launch path — the crash loop
SPEC.md §14 calls the worst possible outcome. And its failure was discarded, so
the app migrated in exactly the two cases the failure exists to prevent.

Two that mislead rather than destroy. The failure classifier searched
SqliteException.toString(), which appends the bound parameters — so a user
whose fuel station is called "Unique Fuel" was told their entry broke a rule
when their disk was full. And a whole trip's odometer could not be corrected
upward, because the new start was measured against the trip's own stale end.

Also: a DST-crossing weekend doubled the implied-rate warning, six scoped watch
queries had no index, watchRecords was 1 + N, and the two watch streams
missing distinct were the ones behind the app shell.

Six of the migration opener's defences cannot be made to fail on this
platform
and are listed by name in migration_guard_test.dart rather than
implied to be proven — closing before restoring, deleting before copying back,
the WAL checkpoint, the sidecars, restore-by-rename, and snapshot retention. The
first four are masked because closing checkpoints the WAL; the last two only
differ when the disk is full.

Deferred

  • No repository passes refuseWith yet. writable_store.dart and
    guardPersist's parameter are the seam and both are tested; wiring it needs a
    composition root that knows the open outcome, which arrives with the app shell
    in EPIC-08.
  • openMigratedDatabase is tested but not wired. appDatabaseProvider
    still constructs AppDatabase() directly. Routing bootstrap through the
    opener is EPIC-08's job.
  • The every-pair migration loop runs zero pairs. Written now so a future
    bump cannot forget the skip paths — the user who goes v1 → v3 without ever
    being on v2 — and its failure message names the fixtures directory and says
    what to assert.
  • Value objects. Money, Distance, Volume and Energy arrive in
    EPIC-06. The progress file lists every canonical-integer field by name,
    including the ones that look like units and are not — a notification time is a
    LOCAL time of day, and wrapping it in a Duration would be the same mistake
    as storing it as an instant.
  • The safety copy is not in SPEC.md §6.2.1's backup envelope, so the import
    path would reject it — which §17's checklist requires it not to. Deferred to
    EPIC-15, which builds that format; writing a file in an invented envelope now
    means reconciling two definitions of it later. This epic owes EPIC-15 the
    numbered-reader mechanism, which it has; EPIC-15 owes it one toBackupFile
    step between the reader and the encoder.
  • A calendar-invalid event date passes the shape GLOB — '2026-02-30'
    displays as 30 February and computes as 2 March. Reachable only from an
    import, whose record-level validation is §6.5 and EPIC-15's. Recorded because
    the GLOB is this epic's.
  • Expense.amountMinor may be negative and is the only money column without
    a >= 0 check. There is a test whose whole job is to say so, so that nobody
    adds the check for consistency and makes a refund unrecordable.

zakariaf and others added 25 commits September 3, 2026 23:36
…power cut

Three of these four do not persist in the file. `journal_mode`, `synchronous`,
`foreign_keys` and `busy_timeout` are per-CONNECTION settings, so they belong in
`setup`, which SQLite runs on every open — not in `onCreate`, which runs once in
the life of the database. The way this goes wrong is quiet: somebody sets them
at creation, sees a green test against a fresh database, and ships an app where
the second launch has no foreign keys and every `ON DELETE CASCADE` in the
schema is decoration. So the foreign-keys test opens, closes and REOPENS the
same file, and asserts on the second connection.

`synchronous = FULL` rather than WAL's default NORMAL. NORMAL can lose the last
committed transactions after a power cut, which is the correct trade for a cache
and the wrong one for hand-entered data that no server holds a copy of
(SPEC.md §2). The fsync is bought deliberately.

The file goes in the application SUPPORT directory, not Documents. On iOS
Documents is user-visible and iCloud-backed, and a half-written WAL syncing to
iCloud is a corruption vector for a file the user cannot regenerate.

Each of the four assertions was seen to fail: removing its pragma turns its test
red, and removing `busy_timeout` also trips the fifth test, which counts the
`PRAGMA` statements in the file. That fifth test is what makes the other four
proofs about the APP rather than about `applyPragmas` — they configure their
connection with the same function `openConnection` passes, and a second inline
`setup:` in the real path would leave them asserting a copy of the behaviour.

`tools/check_drift_confinement.sh` wraps the vendored skill script so CI, the
self-test and a developer call one path, and `check_gates_selftest.sh` gains two
arms: a `package:drift` import under `lib/features/` (the real shape — a feature
file that wants one row type and imports the package to name it) and a
`package:sqflite` import under `lib/data/`, which is refused everywhere rather
than confined. Both were seen to fail.

Three new dependencies, audited before they landed. Neither drift, sqlite3,
sqlite3_flutter_libs nor path_provider reaches a socket: the only network-shaped
packages in the resolved tree arrive through `flutter_riverpod -> riverpod ->
test`, which is a test harness the audit already excludes and which predates
this epic. `sqlite3` is declared directly because `applyPragmas` takes a raw
`Database` — relying on the transitive edge is how a bump becomes a compile
error in a file that never mentioned the package.

Generated Drift code is committed, matching the policy the l10n tree already
uses, and CI gets the gate that makes it a policy: regenerate, then `git diff
--exit-code`. A stale `.g.dart` compiles and runs against yesterday's tables,
which for a migration ladder means a column that exists in the class and not in
the database.

EPIC-05 task 5.1 · SPEC.md §3 Durability, §14 Storage and scale

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…gn key a compile error

Two things this epic assumed it would inherit and did not. EPIC-05's "Where we
are now" lists a Result/Failure spine already in use; there is none in the tree.
It is built here rather than worked around, because Task 5.2 wants `parse`
returning `Result<T, IdFailure>` and every repository method in Task 5.7 wants
`Result<T, PersistFailure>`, so inventing a second vocabulary now would mean
converting between two of them for the rest of the app.

The spine is `error-handling-typed-results` rules 1-4, hand-rolled and
Flutter-free: sealed `Result` with `Ok`/`Err`, an abstract `Failure` carrying a
stable `code`, and exactly two combinators. Two, deliberately — a larger algebra
invites a chain nobody can read, and the exhaustive `switch` is what this
codebase reaches for. `test/policy/typed_failures_test.dart` is the gate for
rule 3: a `String message` on a failure compiles, reads naturally at the call
site, and produces an English sentence on an Arabic screen. It is invisible
until somebody who does not read English opens the app. The gate lists the names
that mean "show this to the user" and not the names that mean "a string was
involved" — `MalformedId.offered` is the input that failed to parse, which is
the typed param the rule asks for, and banning it would have taught people to
avoid the rule rather than follow it.

Then the ids. SPEC.md §3 fixes `<prefix>_<ULID>` as the identity in the
database, in the export file and in every notification payload, with nine
prefixes. The type system carries which is which, so passing a fill-up id where
a vehicle id belongs is refused rather than becoming a foreign key that finds
nothing at runtime. Two of the nine are worth naming because they get confused:
the service ITEM — the thing that reminds — is `rem_`, and the service RECORD is
`srv_`. `svc_` is nobody's, and the test names the entity beside each prefix so
a future reader cannot fix the "wrong" one.

ULID over UUIDv7 for two properties the app actually uses. It sorts as a plain
string, which is where history pagination gets its deterministic tiebreak. And
it is readable: Crockford drops I, L, O and U because a person compares two ids
by eye in an export file or a bug report, and 1/I and 0/O are the pairs that get
mistyped.

The monotonic increment is the subtle half. Two ids minted inside one
millisecond share a timestamp, so without incrementing the randomness rather
than redrawing it they order by their random bits — and history pagination then
returns rows in an order that changes between runs. Three mutations were each
seen to turn the suite red: redrawing instead of incrementing, dropping the
wrong-prefix check, and putting `I` back in the alphabet.

Nothing on the minting path reads an ambient clock or an ambient `Random()`.
Both arrive as constructor arguments and a test greps for it, because
`seeded-determinism-and-golden-vectors` names exactly that as what turns a
failing test into a story about a machine.

EPIC-05 task 5.2 · SPEC.md §3 Identity, timestamps, deletion

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…raints and are not

`Vehicles`, `ServiceItems` and the `Settings` singleton, with every invariant
SPEC.md §3 states put in the SCHEMA rather than in Dart. That distinction is the
whole task: an invariant enforced at the call site is one an import, a migration
or a future repository walks straight past, and this database will be written by
all three.

Every enum is a `CHECK` listing the exact spec spellings, and the spellings live
twice — as a Dart enum in `lib/core/domain/enums.dart` and as a literal that
drift's generator has to be able to read.
`test/data/db/tables/enum_checks_test.dart` closes that gap by parsing the
`IN (...)` list back out of `sqlite_schema` and rebuilding it from the Dart
enum, so adding a 29th `ServiceKind` without touching the table fails there
rather than at a user's insert. Adding a `VehicleType.bicycle` was seen to fail
it.

Two things the tests caught that nothing else would have.

`.references(Vehicles, #id, onDelete: KeyAction.cascade)` compiled, generated,
analysed clean — and emitted no `REFERENCES` clause at all. `service_items`
came out with `"vehicle_id" TEXT NOT NULL` and nothing more, so an item pointing
at a vehicle that does not exist was accepted, and the cascade that Undo depends
on did not exist. The only reason it surfaced is a test that inserts an orphan
and expects a constraint error; nothing in Dart could have.

`.withLength(min: 3, max: 3)` is a DART-side validator on the generated
companion and emits nothing into `CREATE TABLE`. All four currency columns were
unchecked in the database. The exponent that turns 4599 into 45.99 comes from
the code, so a two-letter one does not make an amount odd — it makes it
unreadable.

Both are now gated by `test/data/db/schema_reality_test.dart`, which asks
SQLite what it actually has: no `withLength` in any table file, every column
whose name contains `currency` carries `length(col) = 3` in its SQL, and every
`*_id` column that names another table appears in `PRAGMA foreign_key_list`.
The last one is derived rather than listed, so a foreign key added in task 5.5
is covered without editing the test. Re-planting both traps was seen to fail it.

`service_items` has no `mode`, no `rule`, no `lead_*` and no `notice_months`,
asserted by name. SPEC.md §3 says which axes apply is DERIVED from which
interval fields are non-null; a stored mode is a second answer to a question the
data already answers, and the day it disagrees the engine reads one and the
screen shows the other.

The times are integers, and the two kinds are different. `created_at` and
`updated_at` are UTC epoch milliseconds because they are instants; a
notification time is minutes after LOCAL midnight because it is not — 09:00
stays 09:00 in Tehran and in Toronto, and storing it as an instant would move
it when the user crosses a zone. `updated_at` is clamped to `>= created_at` on
READ, per SPEC.md §3, not blocked on write: blocking would refuse a row whose
only fault is that the device's clock moved backwards, and refusing to save what
somebody just typed at a pump in the rain is the worst available answer to a
clock problem.

The dead-wire-value gate was rewritten a second time. `'persian'` is alive as a
calendar value and dead as a numeral one, and the settings table lists it
legitimately in its `calendar` CHECK — with the `numerals` column immediately
below, so no fixed window around an occurrence can tell them apart. It now reads
backwards from each occurrence to the nearest of the two words, which answers
correctly for a SQL CHECK, for a raw settings map and for `CalmCalendar.persian`
alike.

EPIC-05 tasks 5.3-5.4 · SPEC.md §3 Entities, Enums, Invariants and validation

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
… express

Service records and their lines, fill-ups, expenses and trips — SPEC.md §3
Entities and Invariants. What is worth reading here is what each constraint
prevents, because every one of them is a wrong ANSWER rather than a crash.

`service_records` has no total column, asserted by name. Cost is always the sum
of the lines; a stored total drifts the first time a line is edited, and then
the history screen and the cost dashboard disagree about what a service cost
with nothing to say which one is the receipt.

`service_lines.service_item_id` is `ON DELETE SET NULL` and not cascade. SPEC.md
§3: deleting a ServiceItem never touches history — every referencing line is
rewritten to null and KEEPS its label and amount. Cascading would delete the
record of work that was actually done because the user tidied up a reminder.
The mutation to CASCADE was seen to turn the suite red.

A fill-up ca
8000
rries exactly one of `quantity_ml`, `quantity_g` and `energy_wh`,
and the one it carries matches its fuel kind. Two quantities is a row that means
two things and none is a fill-up with no fuel in it; both break the consumption
maths silently. And without the fuel-kind match an electric fill-up could carry
millilitres, which comes out as litres per 100 km for a car with no tank. CNG is
sold by mass and electricity by energy, so this is not tidiness.

There is no unit-price column, asserted by name. The form takes any two of
{total, quantity, price per unit} and computes the third; only total and
quantity persist, because storing all three guarantees a day when they disagree.

`expenses.amount_minor` is the ONE money column in the schema with no `>= 0`
check, and there is a test whose whole job is to say so out loud — a refund, a
warranty reimbursement or an insurance payout is money coming back, and this row
is the only way to represent it. Without the test somebody adds the check for
consistency and a refund becomes unrecordable.

Zero is accepted where zero is a fact and refused where it is not: a free fill-up
costs 0, a warranty job's line is 0 (the model requires at least one line, so
zero is the only representable "not recorded"), and a fill-up of zero litres is
refused because it divides into the consumption maths.

Every enum spelling is table-driven against `lib/core/domain/enums.dart` — all
seven fuel kinds with their matching quantity column, all ten expense
categories, all four trip purposes — so a typo in a CHECK list fails here rather
than in an export two epics later.

Six constraints were mutated in turn and each was seen to turn the suite red.
The tests were written after these tables rather than before, and the mutation
sweep is what stands in for the red I did not watch; recorded here rather than
left implied.

EPIC-05 task 5.5 · SPEC.md §3 Entities, Invariants and validation

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…ion resolved

SPEC.md contradicted itself and this task had to pick. §3's
`OdometerCorrection.reason` enum lists four values including `unit_mixup`, and
§14 *Edge cases* says in as many words: "`unit_mixup` is removed as a correction
reason." §14 is right and it is the narrower, explicitly-decided statement —
storage is canonical metres and the odometer unit is a per-record fact, so a km
cluster fitted to a miles car needs no offset at all. The reading is entered in
the unit the new cluster shows and converted on the way in.

So the `CHECK` ships three reasons, and **SPEC.md §3 is edited in this commit**
rather than left disagreeing with itself. Widening the CHECK to admit both
would have offered the user a resolution that does nothing, and leaving §3
alone would have left the next reader to rediscover the contradiction. The §3
prose that explained the `unit_mixup` arithmetic is replaced with a pointer to
§14 and a note that the two sections disagreed.

The cumulative odometer is a FUNCTION and never a column. SPEC.md §2 forbids
persisting a derived value, and this is the one where it costs most: a stored
cumulative survives an import and is then wrong forever, with the corrections
applied twice or not at all and nothing to say which.
`cumulativeByReading` is a pure fold with no Flutter and no database, tested
against §3's own worked cases — the 187,412 km cluster swap and the 999,999
rollover — plus the boundary rule that decides where an offset starts: the
correction's own reading is the FIRST on the new scale, so it is corrected too.
A correction naming a reading that is not present is ignored rather than guessed
at; applying its offset to everything would silently move a whole history.

`schema_reality_test.dart` gained the companion half: no column anywhere may be
named for a derived value. `consumption_unit` is exempted by name, because a
stored preference about how a value is DISPLAYED is not a stored value.

The monotonicity guard blocks and the three soft warnings write, and the two are
not interchangeable. A warning that blocked would make the app unusable for the
delivery driver who really did do 900 km yesterday; a violation that wrote would
corrupt the distance history underneath the consumption figures, the projection
and the cost per km at once. A block carries the neighbour's cumulative value
AND its date, because SPEC.md §3's three resolutions all need them and a bare
refusal gives the user nothing to act on.

Two cases the obvious implementation gets wrong, both tested. A backdated entry
must fit under its SUCCESSOR as well as over its predecessor, or the history is
non-monotonic at a point nobody looked at. And a reading dated before the
earliest one is ACCEPTED when its value is lower — that is a used-car buyer
typing "96,000 km, May 2019" out of a service book, and §14 says it must never
require a correction event. Six branches were mutated in turn and each was seen
to turn the suite red, including the same-day guard: without it, dividing by
zero days makes every second entry of the day look impossible, and logging a
fill-up then a reading minutes later is the normal case.

Four indexes, each proven used by `EXPLAIN QUERY PLAN` rather than asserted to
exist. All are partial on `deleted_at_utc_ms IS NULL`, because a soft-deleted
row is invisible to every query in the app. The valuable proof is the second
mutation: reordering `idx_readings_vehicle_order`'s columns leaves the index
existing AND still used, and the plan grows a `USE TEMP B-TREE FOR ORDER BY`. A
test that only checked "uses the index" would have passed it.

The fuel page is keyset, not `OFFSET` — asserted on the query text. `OFFSET`
makes page 50 read 2,500 rows, and it silently skips or repeats a row when
something is inserted between two pages, which for a log people backdate into is
not hypothetical.

`odometer_readings.source_id` is deliberately not a foreign key: it points into
one of five tables depending on `source` and SQLite has no polymorphic
reference. It is named in `schema_reality_test.dart`'s exception list with that
reason, because "it isn't a foreign key" is exactly what somebody says about a
column that should have been one.

EPIC-05 task 5.6 · SPEC.md §3 The odometer, §14 Odometer and data integrity

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…pository

The write path's rule, which every repository in this directory follows:
persist first, republish second. Every mutation is exactly one
`db.transaction`, and the UI learns about it because the watched stream
re-emits — never because the repository pushed an optimistic update. An
optimistic update that a later constraint rejects leaves the screen showing a
row the database does not have, and the test that pins it counts emissions:
exactly two, never three.

Three tests here were written, passed, and proved nothing until they were fixed.
Recording them because each is the shape the TDD rule exists to catch.

The durability test used an in-memory database, where "written" and "committed"
cannot be told apart because both connections are the same one. It opens a real
file now, writes through one connection, closes it, and reads through a second.

The closed-database test closed an in-memory database and expected a failure —
but closing an in-memory database destroys it and drift opens a fresh empty one,
so the write succeeded. It points at a path that is a DIRECTORY now, which is
also a better test: it produces a disk failure rather than a constraint one, so
it proves the classification as well as the catch.

And the ValueEquality type test compared classes with different-length props
lists, so `_listEquals` returned false on the length alone and the
`runtimeType` check could be deleted without the suite noticing. The two classes
now have identical props, and removing the check was seen to turn it red.

`ValueEquality` exists because hand-rolling `==` and `hashCode` per model means
writing every field twice, and the failure is silent in the direction that
matters: a field added to `==` and forgotten in `hashCode` gives two "equal"
objects different hashes, which corrupts a Set and a Map key rather than
throwing. One list, read by both. No package — `equatable` is a dependency for
eleven lines and `freezed` is a second code generator for a project that
already commits Drift output.

`guardPersist` is the only place a driver exception becomes a value, and all
three of its arms are tested directly rather than through a repository. Two of
them cannot be reached any other way: the app opens its connection with
`NativeDatabase.createInBackground`, so on a device every exception crosses an
isolate boundary and arrives wrapped, and a test using a direct
`NativeDatabase` never produces that shape. Without the third arm a user's
constraint failure would arrive on a real phone as an unclassified write error
and read as "something went wrong". It catches `Exception` rather than naming
`DriftRemoteException`, whose type lives in drift's experimental `remote.dart`
and whose `toString()` carries the cause the classifier reads anyway —
and `on Exception` is still narrow where it counts: an `Error` passes straight
through, so a `StateError` from a mapper crashes in debug instead of becoming a
failure value the UI shows while the data quietly stops matching.

The models live in `lib/core/domain/models/`, not `lib/domain/` as EPIC-05's
text says. `test/policy/structure_test.dart` sanctions seven top-level
directories and `core` is the one labelled "pure Dart domain — no Flutter,
ever", which is exactly what these are. The gate is an existing deliberate
decision from EPIC-01 and it wins over the epic's prose.

Every derived value on those models is a getter and a column nowhere: a service
record's total is the sum of its lines, a service item's axes come from which
interval fields are non-null, a trip's distance prefers its odometer endpoints
and falls back to a typed figure only when both are absent. Four of them were
mutated and each was seen to turn the suite red — including the one that matters
most, `...lines` in the record's props: without it a watched stream would skip
the rebuild after a line was edited and the screen would show yesterday's total.

EPIC-05 task 5.7 (part) · SPEC.md §3 Entities, Derived values

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
… signature

The write path, finished. Every mutation is one `db.transaction`, every read is
scoped to a vehicle, and nothing above `lib/data/` ever sees a Drift type.

Three findings the tests forced, each of which changes the code rather than the
comment.

**Drift's stream invalidation is TABLE-level.** A write to vehicle A re-runs
every query over that table, including vehicle B's — the `WHERE` does not enter
into it. The epic asks that writing to B not wake A's subscription, and with
drift the query re-runs either way. What CAN be controlled is whether the
subscriber wakes, and that is what the models' value equality buys: `.distinct`
on every watch stream turns "the query ran again" into "nothing changed, do not
rebuild". Removing it from the record stream was seen to turn the scoped-stream
test red. The scope still earns its place — the re-run is an indexed lookup
rather than a scan — but it is not what stops the rebuild, and the comment says
so.

**The edit exclusion is load-bearing, and the first test for it was not.**
`saveReading` drops the row being edited from the comparison set. Leaving it in
puts a stale copy in the sorted order where the successor belongs, and because
the cumulative map is keyed by id that copy reports the NEW value — so the check
compares the reading to itself, finds no conflict, and lets an edit through that
puts 200,000 km before a stored 195,000. The first test only edited the LAST
reading, where the stale copy has nothing after it and the bug cannot show; it
passed with the exclusion deleted. The replacement edits a middle reading.

**Two of `guardPersist`'s three arms cannot be reached through a repository.**
The app opens its connection with `NativeDatabase.createInBackground`, so on a
device every exception crosses an isolate boundary and arrives wrapped, and a
test using a direct `NativeDatabase` never produces that shape. Without the
third arm a user's constraint failure would arrive on a real phone as an
unclassified write error and read as "something went wrong". `guard_test.dart`
drives all three directly, and each was seen to fail when disabled.

`no_drift_in_signatures_test.dart` is the other half of
`tools/check_drift_confinement.sh`. The script proves no file above `lib/data/`
imports drift; this proves nothing inside `lib/data/` hands a Drift type UP —
which the grep cannot see, because a caller of a method returning `VehicleRow`
never writes the import. Two bugs in the test itself were found by its own guard
tests: a line scanner read a wrapped private helper as public API, and a `\b`
before `$` never matches, so `$VehiclesTable` was silently unmatched. Planting a
public `Future<VehicleRow?> rawById(...)` fails it.

The models live in `lib/core/domain/models/` and `AppSettings.isQuiet` handles
the window that wraps midnight, which is the normal case: 21:00 to 08:00 read as
a plain `from <= x < to` makes the whole night loud.

`providers.dart` splits `autoDispose` deliberately. The seven vehicle-scoped
families dispose with the screen that asked for them — without it, opening four
vehicles' histories leaves four live queries for the rest of the launch — and
`vehiclesProvider` and `settingsProvider` do not, because the app shell reads
both all session and disposing them would rebuild the query on every tab change.
Both directions are asserted, and both were seen to fail.

EPIC-05 task 5.7 · SPEC.md §3 Entities, Derived values; §14 Storage and scale

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
SPEC.md §3: "Delete is immediate and permanent to the user; soft in storage only
for the length of the snackbar." Three consequences, each a rule in this file.

**Undo restores by TIMESTAMP, not by vehicle.** One stamp is written across the
whole cascade in one transaction, and the undo matches on it. Restoring
"everything currently deleted for this vehicle" would resurrect a fill-up the
user removed five minutes earlier — a data change nobody asked for, arriving
under a button labelled Undo. The test deletes a fill-up first, deletes the
vehicle, undoes that, and asserts the fill-up stays gone; making the undo match
on `vehicle_id` alone was seen to fail it.

**A purged row is unrecoverable, so the cutoff is not decoration.** `purgeDeleted`
takes a timestamp from the caller's injected `Clock` and never runs a timer of
its own: a timer inside the data layer fires on a schedule no test can control,
and this is the one operation here that cannot be taken back. Rows deleted after
the cutoff are left alone, because their undo window has not closed. After a
purge no `deleted_at` survives anywhere, which is SPEC.md §3's stated invariant —
no bin, no tombstones, nothing deleted in the export.

**`eraseVehiclePermanently` is a separate method, not a flag.** A boolean
parameter meaning "and this one is unrecoverable" is a boolean somebody passes
wrong once.

`service_lines` is deliberately absent from the cascade list and has no
`deleted_at` column at all, asserted by a test that says why: it is a child row
that lives and dies with its record, the schema's `ON DELETE CASCADE` removes
it, and a `deleted_at` here would be a second answer about whether a line exists
— one that disagrees with the first the moment a record is undeleted.

The fixture guard earns its place. The stamp test walks seven child tables, and
the first version populated four of them; `DISTINCT deleted_at_utc_ms` over an
empty table is an empty set, so three tables were being "checked" while holding
nothing. It now asserts every table has a row BEFORE the delete, which is what
found `odometer_corrections`, then `expenses` and `trips`.

Four behaviours were mutated and each was seen to turn the suite red, including
the one that would be least visible in review: dropping `AND vehicle_id = ?`
from the cascade update, which soft-deletes every vehicle in the garage.

EPIC-05 task 5.8 · SPEC.md §3 Identity, timestamps, deletion

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…a made-up id

SPEC.md §3: "EVERY record carrying an odometer emits a reading: one table
computes distance history and enforces monotonicity." So a fill-up, a service,
an expense and a trip each contribute theirs — and if one does not, the
consumption maths, the projection and the cost per km are all computed from a
history with a hole in it, which reads perfectly and is simply wrong.

`odometer_fan_out.dart` is the only writer of a non-manual reading. Four
repositories writing their own would be four chances to disagree about the id,
the source or the date, and the symptom would be duplicates nobody can
attribute.

The first version synthesised the reading's id from its parent's —
`odo~fil_01J…` — which makes the upsert a one-liner and breaks two things.
SPEC.md §3 fixes every id in the app as `<prefix>_<ULID>`, in the database, in
the export file and in every notification payload; and `RecordId.parse` rejects
that shape, so `odometerReadingFromRow` would throw on the way back out and the
row could be written and never read. It mints a real ULID now and finds the
existing reading by `(source_id, source)`, which is the better key anyway: a
trip carries two readings that differ by `source` alone, so one lookup shape
covers all five parents.

A null odometer removes the reading rather than leaving it. An insurance premium
paid online has no odometer to record, and clearing one the user entered by
mistake has to take the reading with it — a number in the distance history that
nothing on screen explains is worse than no number.

An open trip emits one reading and a closed one emits two. The end reading is
removed while the trip is open rather than left holding yesterday's number.

Every call runs inside the parent's transaction, and there is a test for what
that buys: a service record with a bad line rolls back, and its reading rolls
back with it. Written separately, the reading would survive and point at a
record that does not exist.

Three behaviours were mutated and each was seen to turn the suite red, including
the lookup key — with the wrong one, editing a fill-up's odometer leaves the old
reading behind and the distance history grows a phantom entry every time
somebody fixes a typo.

EPIC-05 task 5.9 · SPEC.md §3 Entities, The odometer

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
SPEC.md §6.3 and §17's data-safety gate. The machinery that makes every future
schema change provable is built now — the snapshot, the generated ladder, the
era-correct classes, the every-pair loop and the CI gate — because building it
at v2 means building it while somebody's eight years of service history is
already in the file.

`build.yaml` did not exist, so `drift_dev make-migrations` exited with "No
databases found in the build.yaml file" and the entire snapshot mechanism was
unavailable. That is a thing you find out on the day you need to migrate, not
before. It exists now and names the database, the schema directory and the test
directory.

The `onUpgrade` order is the contract, and it is the shape `run-migration`
specifies for a reason. Foreign keys go OFF **before** the transaction, not
inside it: SQLite silently IGNORES `PRAGMA foreign_keys` while a transaction is
open, so a migration that turns them off in the wrong place runs with them on,
and a step that rebuilds a table drops every child row that referenced it —
silently, and reported as a successful migration. Afterwards
`PRAGMA foreign_key_check` runs and throws if it finds orphans, because that
pragma REPORTS rather than refuses: without the explicit check a migration that
orphaned rows would commit and look fine, and the rows would be gone from every
query while still occupying the file. `beforeOpen` turns keys back on
unconditionally.

`kLatestSchemaVersion` is hand-written because `drift_dev schema steps` does not
emit one — it generates the ladder and leaves the number to the app, which makes
it exactly the kind of constant that drifts. Both directions are gated and both
were seen to fail: bumping the constant with no snapshot (which makes
`stepByStep` throw "Unknown migration from 1" on the device of every user who
had the old version), and exporting a snapshot without bumping it (which means
the migration never runs and the app reads columns that are not there).

The every-pair loop runs zero pairs at v1 and that is the point. It is written
once, now, so a future bump cannot forget the skip paths — the user who goes
from v1 to v3 without ever being on v2. Its failure message names the two
fixtures directories and says why a shape test is not enough: a shape test reads
zero rows, so it cannot tell a step that copied everything from one that copied
nothing.

`tools/check_schema_freshness.sh` runs in the `repo` CI job, which has no
Flutter toolchain, so the check is in the lane that finishes in 20 seconds on
every push rather than only in the one that needs a full `pub get`.

The era-correct classes are generated with `--data-classes --companions` and
committed. Both flags are load-bearing, and generating them at test time would
generate them from TODAY's schema — which is the one shape a migration test must
not use.

EPIC-05 task 5.10 · SPEC.md §3 Durability, §6.3 Versioning and migration, §17

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…be proven

SPEC.md §6.3.3, §6.4.4, §14, §17's data-safety gate, `CLAUDE.md` rule 3. This is
the task the epic exists for: losing eight years of service history is the worst
bug this app can have, and a migration is the only code path that can do it in
one step.

The first version of the test was worthless and did not look it. It injected a
migration that throws, asserted the file was byte-identical afterwards, and
passed — with the restore deleted, with the close-before-restore ordering
reversed, with the WAL checkpoint gone and with the `-wal`/`-shm` sidecars
dropped from the snapshot. Every mutation stayed green.

The reason is that drift wraps `onUpgrade` in a transaction, so a step that
throws before committing is rolled back by SQLite and the file is untouched
whether the snapshot works or not. The snapshot exists for the OTHER case: a
migration that commits and then fails. That is not hypothetical — it is the
shape of `AppDatabase.onUpgrade` itself, which runs `stepByStep` in a
transaction and then throws if `PRAGMA foreign_key_check` finds orphans, after
the commit. The test now has both: `_ThrowingDatabase` for the transactional
case, and `_CommittingThenThrowingDatabase`, which DELETES every vehicle,
commits, and then throws. Against that one, removing the restore loses the
user's garage and the app comes up empty and healthy-looking.

Four defences still cannot be made to fail here, and the test says so in place
of claiming otherwise. Closing the connection checkpoints the WAL into the main
file, so by the time the restore runs it is overwriting a file that is already
complete — which masks the close-before-restore ordering, the delete-before-copy
pass, the checkpoint and the sidecars all at once. They stay, because each
covers a case this test cannot produce: a checkpoint that fails because a reader
holds the WAL, a process killed between the commit and the close, a platform
where deleting an open file is not benign. What IS asserted is the end state —
after a rolled-back migration the file is the old one and no sidecar beside it
holds the new one.

The JSON safety copy is written through the NUMBERED reader for the version ON
DISK, never through the code that is about to migrate. A copy taken by that code
is a copy taken through the crash: if the new mapper misreads a column, the copy
carries the same misreading and the escape route is as broken as the thing it
was escaping. Readers are never deleted — a user who skipped four updates opens
a v1 file with a v5 binary — and a version this build does not know returns null
rather than being read with the nearest reader, because a corrupt safety copy is
worse than none: it looks like an escape route.

The file is named for the VERSION and not a timestamp, per SPEC.md §6.4.4, so a
user who has updated four times has one file and not four in storage they cannot
see or clear. An existing `odova-safety-import-*` and `odova-safety-wipe-*` are
left untouched, asserted, because an import that ate the copy a wipe left is the
exact failure §6.4.4 is written to prevent.

The raw file work goes through `package:sqlite3` rather than drift, for the same
reason the readers are numbered: it all happens before drift opens anything, and
routing it through drift would mean opening the database with the code that is
about to migrate it.

`DegradedMode` is the state a failed migration leaves behind — reads work,
writes are refused, and the banner names where the copy went. A crash loop is
the worst available outcome: the user cannot open the app to export their data,
and the only remedy left is uninstalling, which deletes it.

EPIC-05 task 5.11 · SPEC.md §6.3.3, §6.4.4, §14, §17

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…oracle

Two halves of task 5.11 that the guard commit left out.

**The write refusal.** SPEC.md §6.3.3 and §14: after a failed migration the app
comes up read-only rather than crash-looping, and this is the seam that makes
that true rather than a promise in a banner. One wrapper rather than a check in
each repository — seven repositories with their own guard is seven chances for
one added later to be missing it, and the symptom would be a single screen that
can still write into a database the app has decided it does not understand.
The refusal is checked BEFORE the body runs: a write that reached the database
and was then rolled back has still touched that file.

Adding `StoreReadOnly` made `test/data/failures/persist_failure_test.dart` stop
compiling until the new variant was handled, which is the entire value of a
sealed switch with no `default:`. A `default:` would have silently mapped a
read-only store to whatever generic message the last case produced.

**The zero-record-loss oracle**, SPEC.md §17's data-safety gate. Row counts AND
a content hash, before and after. Counts alone would not notice a migration that
copied the right NUMBER of rows with the wrong values in them — which is what a
mis-mapped column does, and it is the failure that survives review because
everything still looks populated. There is a test for the oracle itself:
changing a single cost by one cent must change the hash while the counts stay
identical.

At v1 the ladder is a no-op and what is being proven is the harness. From the
first bump on, this is the test that catches a step that copied nothing —
planting a `DELETE ... WHERE rowid % 100 = 0` before the open was seen to fail
it.

The fixture is seeded from one integer and its determinism is asserted in both
directions: the same seed twice gives the same hash, and a different seed gives
a different one — a fixture that ignores its seed is a fixture that tests one
shape forever. Its distribution is four vehicles with eight years of fill-ups
and readings rather than 12,000 vehicles, because the second would exercise a
table a real household barely touches.

The duration is printed and not asserted. §17's budget is 3 seconds on the FLOOR
device; CI is not that device, and a hard timing assertion on a shared runner is
a flaky test rather than a gate. It runs in 3 ms today.

`crypto` is a new DEV dependency and never ships. Audited: no network path.

EPIC-05 task 5.11 · SPEC.md §6.3.3, §14, §17 Data-safety gate

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
The three sections worth reading are the spec contradiction that was resolved
rather than worked around, the two Drift APIs that look like schema constraints
and emit nothing, and the six tests that passed while asserting nothing.

That last list is the point of the file. Every one of them was written, run,
seen green, and only found by mutating the code underneath it — including the
migration test, which asserted a byte-identical file after a failed migration
and passed with the restore deleted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-05's own text says EPIC-06 will look here for two things, and this is the
first: every int field carrying a unit, so the value-object swap knows exactly
what it is replacing.

The list that matters most is the last one — the fields that look like units and
are not. Wrapping a notification time in a Duration would be the same mistake as
storing it as an instant: it is a LOCAL time of day, and 09:00 has to stay 09:00
when the user crosses a zone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
SQLite's default is NO ACTION, which is not a decision — it is the absence of
one, and it surfaces as a constraint failure at delete time rather than as the
cascade or the detach the design intended. SPEC.md §3 names both behaviours: a
vehicle CASCADES to its history, and a deleted ServiceItem SETS NULL on its
lines so the work that was actually done survives being tidied up.

Derived from PRAGMA foreign_key_list rather than listed, so a foreign key added
in a later epic is covered without editing the test. It also checks the CREATE
TABLE text, so a reviewer reading a table file sees the action rather than
having to ask SQLite. Removing the cascade from trips.vehicle_id was seen to
fail both halves.

EPIC-05 · SPEC.md §3 Identity, timestamps, deletion

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…repo

`**/failures/` was added for golden diff artefacts, which land in
test/ui/calm/goldens/failures/. It also matched lib/data/failures/ and
test/data/failures/ — the sealed PersistFailure family that nine files in the
data layer import, and its test.

Neither was ever committed. `git status` read clean, the branch compiled
locally against the working tree, every gate passed, and a fresh clone would not
have built at all. A pattern wide enough to catch a directory name somebody will
legitimately want is a pattern that removes source from the repository without
saying so.

Scoped to the goldens directory it was written for. The golden artefacts are
still ignored — planting a PNG there confirms it — and the two recovered files
are now tracked.

Found by the /simplify reuse pass, which noticed that a file it was asked to
review was not in `git ls-files`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…able skipped it

`/simplify`'s altitude pass found the hole and EPIC-05 task 5.9 had named the
test that would have caught it. `checkReading` had exactly one call site,
`OdometerRepository.saveReading`. The fan-out writes into `odometer_readings`
with a raw upsert and never consult
8BD0
ed it — so a fill-up, a service, an expense
or a trip whose odometer went backwards was accepted, and the distance history
they feed was non-monotonic from that point on. That is a wrong consumption
figure, a wrong projection and a wrong cost per km, all of them
plausible-looking, from a save the app reported as successful.

`checkDerivedReading` runs BEFORE the parent's transaction opens, in all four
repositories. Before, rather than inside, because `syncDerivedReading` cannot
refuse: throwing from inside a transaction surfaces through `guardPersist` as
an unclassified write error rather than as the typed
`OdometerWouldGoBackwards` that SPEC.md §3's three resolutions need. Refusing
first also gives task 5.9's exact wording — "leaves neither the fill-up nor a
reading behind" — for free.

It reads the vehicle's own unit and purchase odometer rather than taking them as
arguments. The alternative put the same two parameters on four `save`
signatures and on every call site in the app, for values one primary-key lookup
away. A null `distance_unit` means inherit from Settings and this does not chase
that: the unit affects only the km/mi mix-up WARNING, never the block, and a
warning raised by a derived reading has nowhere to surface yet, so the fallback
costs one unshown warning rather than a wrong answer.

The proposed reading reuses the REAL row's id and created-at on an edit.
`compareReadings` breaks a same-date tie on the id, so a proposal carrying an
invented id sorts at an arbitrary point among its own neighbours — with the
first version's synthetic string it happened to sort BEFORE the row it was
replacing, which is why the lowering-edit test passed with the exclusion
deleted. Diagnosed by printing the stored row rather than assumed benign.

Both halves are now separately proven. The distinguishing case is an edit
UPWARD past a later reading: the stale copy sits in the sorted order where the
successor belongs and reports the proposed value, so the check compares the
reading to itself and lets 187,000 km through in front of a stored 186,600.

`DerivedReadingNotEditable` existed as a failure variant with no code path
returning it — the sealed-family test's exhaustive switch was reporting coverage
the app did not have. `saveReading` now refuses a non-manual source. `import` is
editable alongside `manual`, because an imported reading has no live parent in
this database to follow and refusing it would make a restored backup
permanently uncorrectable.

`softDeleteDerivedReadings` and `undoDeleteDerivedReadings` are deleted. They
had no caller and no test: the vehicle cascade stamps `odometer_readings`
wholesale by `vehicle_id`, and no parent repository has a per-row delete for
them to hang off. Twenty lines of untested delete SQL whose stated contract was
documented in three places and enforced in none.

EPIC-05 task 5.9 · SPEC.md §3 The odometer, Invariants and validation

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…app shell

Three `/simplify` findings that turn out to be the same finding.

`.distinct(valuesEqual)` was a convention at nine call sites, and the two that
had forgotten it were `VehicleRepository`'s — where `vehiclesProvider` is the
one provider deliberately NOT autoDispose, alive for the whole session and
feeding the app shell. So the single most-subscribed stream in the app was the
one that rebuilt on every write to `vehicles`, including a `sortOrder` nudge or
a `notificationsMuted` toggle on a car the user is not looking at.
`SettingsRepository.watch` used a bare `.distinct()`, a third idiom for the
same intent. All of them go through `watchList`/`watchOne` now, so a stream
added in a later epic gets the behaviour by construction rather than by
remembering, and the three-paragraph explanation of WHY lives on the helper
where the next reader will find it.

`watchRecords` was 1 + N queries per emission and the N ran before `distinct`
could discard them. Sixty service records meant sixty-one queries, on every
write to `service_records`, including for a vehicle the user is not looking at.
One `WHERE service_record_id IN (…)` and a group in Dart; `idx_lines_record`
already served it.

The no-Drift-in-signatures gate had two bugs of its own, both surfaced by
routing through the helper and both now covered by their own test. A top-level
function's WRAPPED parameter list is indented two spaces and looked exactly
like a class member, so `watch.dart` — which has no class and legitimately
takes a `Selectable`, being the shared query helper inside the data layer —
reported three violations. And an expression body wraps as `watchAll() =>
watchList(`, putting the `=>` mid-line, so the signature accumulator swallowed
the whole body and matched every Drift type inside it. Re-planting a public
`Future<VehicleRow?>` still fails the gate.

`watchOne` on the repository is `watchById` now, because the shared helper owns
the name and the two meant different things.

EPIC-05 · /simplify findings (reuse 13, efficiency 2 and 4, altitude 4)

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…ven copies

The two findings worth the commit are gates, not tidying.

**Every field of a value type is now checked against its `props`.**
`ValueEquality` removed the duplication between `==` and `hashCode` but not the
one between the FIELD LIST and `props` — and that one is worse. A field declared
and forgotten in `props` makes two different records compare equal, and every
watch stream in the data layer de-duplicates on that equality, so the
consequence is a real edit that never reaches the screen with the database
already updated. `Vehicle` has thirty entries in that list. Removing
`notificationsMuted` from it was seen to fail the gate.

That test found a bug in itself first: the props parser needed a trailing comma
to match, so `[a, b]` on one line yielded only `a` — and the completeness check
passed anyway over a parser that had found half the entries. Its own guard test
is what caught it, which is the second time on this branch a grep-style gate has
been wrong in a way only a guard test could see.

**The cascade list is derived from the schema.** `vehicleChildTables` is
hand-maintained and the delete path is raw SQL over it, so nothing gated its
completeness — the progress file records that `odometer_corrections` was missing
from the first version and was found only because a fixture assertion happened
to walk it. The test now computes the set from `PRAGMA table_info`: every table
carrying both a `vehicle_id` and a `deleted_at_utc_ms`. `service_lines` is
excluded structurally rather than by name, because it has neither. Deleting an
entry from the constant fails it.

The rest is duplication the reuse pass named.

Ten failure classes hand-rolled `==`/`hashCode` — about eighty lines — in the
two families added by this epic, while `ValueEquality` was added by the same
epic for exactly that and every other value type on the branch already used it.
`RecordId` keeps its hand-rolled pair with a comment saying why: the mixin
compares `runtimeType` first, and a `RecordId` from the kind-agnostic
`RecordId.parse` has to equal the `VehicleId` a caller minted.

`storeIsWritableProvider` and `writeRefusalProvider` were two derivations of one
boolean in two files. The typed one survives — a bool cannot carry the versions
the banner needs — and a caller wanting the bool reads `!= null`.

`large_fixture.dart` retyped the 32-character Crockford alphabet; it imports
`crockfordAlphabet` and `ulidLength` now. Two copies of that alphabet is the
shape that drifts silently: a fixture minting a body the real `isUlid` rejects
would pass every migration test and fail nowhere useful.

Two test helpers went back to the shared ones: `_sourceOf` was
`sourceWithoutLineComments` byte for byte, and a Flutter-free-imports check used
a substring search where `importUrisIn` exists — the substring version turns red
for a doc comment that NAMES the package in order to explain why the file does
not use it.

Removed a test asserting that a sealed switch is exhaustive by looping its
cases. Exhaustiveness is a compile-time property; the fact that
`writeRefusalFor` compiles is the proof, and adding a third mode breaks the
build rather than that test. It could not fail for any reason another test in
the same file would not catch first.

EPIC-05 · /simplify

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
CLAUDE.md §5 requires every finding to be applied or answered in writing, and
'answered' to be a sentence saying why the finding is wrong or why the cost is
not worth paying.

The pass paid for itself twice: a gitignore rule had removed the PersistFailure
family from the repository — a fresh clone would not have built — and four of
the five write paths into the readings table were skipping the monotonicity
guard, which EPIC-05 task 5.9 had named a test for that did not exist.

Nine findings are answered rather than applied. The one worth reading is the
test-fixture duplication: it is real, and consolidating it now means doing it
twice, because EPIC-06 changes every one of those models.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
`DateTime.parse('2026-03-28')` returns a LOCAL time. Across a European
spring-forward, two dates two calendar days apart differ by 23 + 24 hours —
which `inDays` truncates to 1. The implied-rate warning then DOUBLES: 2,200 km
over that weekend is 1,100 km/day and entirely ordinary, and it was reported as
2,200 km/day and flagged.

A false warning is not a blocked save, but it is the app telling a delivery
driver their own odometer looks wrong, twice a year, on a weekend they worked —
and this app's whole proposition is that it does not accuse the user on thin
evidence.

EPIC-04 had already solved this and written down why: `wholeDaysBetween` in
lib/core/l10n/relative_date.dart anchors both dates to UTC midnight, and its doc
comment says "a 23-hour day across a daylight-saving boundary is still one
day". The odometer guard was doing its own arithmetic and did not get the
benefit. It calls the same helper now.

The test pins both boundaries: 1,100 km/day across the spring-forward must NOT
warn, and 5,000 km/day across the autumn fall-back must. Reverting to the local
arithmetic was seen to turn it red.

EPIC-05 · /code-review · SPEC.md §3 Invariants and validation

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
A 20,000-id burst inside one millisecond stays sorted and unique. The monotonic
increment carries 80 bits so it does not run out, but "does not run out" is a
claim about an overflow path that wraps to zero and would silently break sort
order if it were ever reached. Twenty thousand is far beyond any real burst — an
import is the worst case — and well inside the range.

And the id is a TIEBREAK, never the app's clock. A ULID sorts by its timestamp,
so a clock that steps backwards mints an id that sorts before its predecessor.
That is inherent to the scheme and it is not this app's problem: nothing orders
by id alone. `compareReadings` sorts by (occurred_on, created_at, id) — SPEC.md
§3's order — and created_at comes from the same clock, so the two move together
and the id only ever separates a genuine tie. Asserted rather than assumed,
because the opposite assumption is the one somebody makes later.

EPIC-05 · /code-review

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
… prose

`_classify` decided between "your data is wrong" and "the disk is full" by
searching the exception message for 'constraint failed', 'foreign key' or
'unique'. That is the difference between a fix the user can make and one they
cannot, decided by English prose a future SQLite could reword.

SQLITE_CONSTRAINT is 19 and says so in a number. Where the exception itself
survives — the direct arm and the DriftWrappedException arm, which carries its
cause — the code is read. The string matcher stays for the isolate arm alone,
where a DriftRemoteException carries its cause as text and there is no code left
to read.

Two cases the string version got wrong and the code version does not: a
constraint failure phrased without any of those three words, and a disk failure
whose message happens to contain one of them. Both are now tests, and reverting
to the string path was seen to turn them red.

EPIC-05 · /code-review

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…history

`/code-review` ran two adversarial passes over the epic's diff. Both reproduced
their findings with throwaway tests rather than reasoning about them, and five
of the seven are the failure class CLAUDE.md rule 3 puts above every feature.

**A re-parented record stranded its reading on the old vehicle, with the new
vehicle's odometer.** The fan-out's upsert keys on `(source_id, source)`, which
is vehicle-INDEPENDENT, and `vehicle_id` was not in the `DO UPDATE SET` list.
Moving a fill-up to another car updated its reading in place: the row stayed on
the old vehicle and took the new one's number. The old car's history then
carried a 5,000 km reading among its 100,000 km ones — non-monotonic at a point
no guard had looked at, because the guard had validated against the NEW vehicle
— and the new car's fill-up had no reading at all.

**Clearing an odometer destroyed a correction.**
`odometer_corrections.from_reading_id` is `ON DELETE CASCADE`, and the reading a
correction anchors to is usually a DERIVED one — a fill-up is the commonest
reading source and a cluster gets swapped between fill-ups. The null-odometer
path hard-deleted the reading, SQLite cascaded, and +187,412 km of offset left
every later reading. The save returned success. It is soft-deleted now, so the
row survives for the foreign key and the purge removes the pair together, after
the Undo window, rather than silently on an edit.

**A failed restore on a full disk left neither the database nor the snapshot.**
`_restore` deleted the live files and then COPIED the snapshot back — and a
device that is nearly full is exactly when a migration fails, so the copy can
throw ENOSPC after the delete. A `finally` then deleted the snapshot on every
path. Next launch: no database, so a brand-new empty one, looking like a fresh
install. It renames now — atomic within a filesystem, needing no free space —
and the snapshot is held until the restore has completed. `close()` throwing on
a dead connection no longer skips the restore either.

**The safety copy could throw into the launch path.** `SELECT *` throws
`SqliteException` for a missing table and `JsonEncoder.convert` throws an
ERROR; the catch was `on FileSystemException`, so both escaped a function
documented as never throwing, out through `openMigratedDatabase` and into the
app's entry point. A database with `user_version = 1` and a missing table — a
process killed during first-run schema creation — hit it on every launch. That
is the crash loop SPEC.md §14 names as the worst possible outcome.

**And the copy's failure was discarded.** `final (file, _) = …` meant the app
migrated in exactly the two cases the failure exists to prevent: a database from
a build this binary has no reader for, and a disk with no room for an escape
route. SPEC.md §6.4.4 says "no exceptions". The write is atomic now too —
temp file then rename — because `writeAsString` truncates, so a second attempt
destroyed the first attempt's copy before producing a replacement.

**The failure classifier read the user's own typed values.** On a real device
the exception does not survive the isolate boundary — drift serialises it as
`toString()` — so the string arm is the one the app uses, and
`SqliteException.toString()` appends the failing statement AND ITS BOUND
PARAMETERS. Searching that for "unique" told anybody whose fuel station is
called "Unique Fuel" that their entry broke a rule when their disk was full,
and put their free text into a field documented as "which invariant, in this
app's words". It parses the result code out of the text now.

**Deleting a correction was hard and unscoped.** The table carries
`deleted_at_utc_ms`, every read filters on it and the cascade lists it first —
and this bypassed all of it for the single highest-leverage row in the odometer
history, with no Undo to offer beside the exposures it returns. The `WHERE` was
`id` alone, so a mismatched pair deleted another vehicle's correction and
reported the exposures for the wrong car.

`purgeDeleted` no longer runs sixteen full-table scans to compute what
`customUpdate` returns, and its doc now says what the map means: rows this
statement removed, not rows that left — the cascade's are invisible to it.

Every fix was mutated and watched go red, except the restore's rename and its
snapshot-retention, which only differ when the disk is full. Those two join the
four already recorded in `migration_guard_test.dart` as correct-but-unprovable
here, listed by name rather than implied to be proven.

EPIC-05 · /code-review · SPEC.md §3, §6.4.4, §14, §17

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
Nine fixed, two deferred with reasons. Five of the nine were ways to lose or
corrupt a user's history, and every one of them returned SUCCESS to the caller —
which is why the list records the consequence rather than the code.

The two deferrals are honest ones. The safety copy is not in the backup file
format because that format is EPIC-15's and does not exist yet; writing a file
in an invented envelope now means reconciling two definitions of it later. And
a calendar-invalid date passing the shape GLOB is reachable only from an import,
whose record-level validation is also EPIC-15's — recorded here because the GLOB
is this epic's.

The verified-not-bugs list is there so the next reviewer does not re-chase
twelve things two reviewers already reproduced and cleared.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
@zakariaf
zakariaf merged commit f75926e into main Sep 4, 2026
4 checks passed
@zakariaf
zakariaf deleted the epic/05-persistence-and-migrations branch September 4, 2026 00:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0