diff --git a/AGENTS.md b/AGENTS.md index f9be2e8e..23250f9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -865,6 +865,24 @@ the chain is built before anything subscribes. When the order matters, test the because the success path cannot tell the two apart. `RxFlowsTest` shows how, with a stand-in that writes when called. +### 24. A deleted row is still in the file until a checkpoint, and a PRAGMA cursor runs only when read + +Android's SQLite has `secure_delete` and `auto_vacuum` on, so a delete zeroes the row and frees its +pages. **But the database is in WAL mode, and all of that happens in the log.** Until a checkpoint, +the main file still holds the pages from before the delete, and the `-wal` file still holds the +frames that inserted the rows. Anyone reading the files finds what the user removed. Measured on the +managed device: after a delete, the rows are readable in both files; after a checkpoint, in neither. + +**`sqlite.query("PRAGMA wal_checkpoint(TRUNCATE)").close()` runs nothing.** An Android cursor +executes when it is first read, so a query that is closed unread never reaches SQLite. #315 shipped +that line after `VACUUM`, and its tag removal left every row in the WAL with no error anywhere. Read +the row (`moveToFirst()`), and do the same for any `PRAGMA` run for its effect. + +`DatabaseCompaction` is the one place this is done: `checkpoint` after an ordinary delete, `now` +(`VACUUM` too) after one the user asked for. `freelist_count` is no help in deciding when: with +`auto_vacuum` on it is always 0. `CompactingAfterDeletingHistoryTest` reads the files byte for byte +for text only the deleted rows carried, and both of its tests fail with the cursor left unread. + --- ## Building and testing diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/CompactingAfterDeletingHistoryTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/CompactingAfterDeletingHistoryTest.java new file mode 100644 index 00000000..e5682f97 --- /dev/null +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/db/repo/CompactingAfterDeletingHistoryTest.java @@ -0,0 +1,173 @@ +package dev.wander.android.opentagviewer.db.repo; + +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.content.Context; + +import androidx.room.Room; +import androidx.room.RoomDatabase; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.concurrent.TimeUnit; + +import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; +import dev.wander.android.opentagviewer.db.room.entity.LocationReport; +import dev.wander.android.opentagviewer.db.room.entity.OwnedBeacon; + +/** + * Deleted history does not stay readable in the database file. + * + *

Until a checkpoint, a deleted row's bytes stay in the main file's old pages and in the + * write-ahead log, so anyone reading the files directly finds the positions somebody chose not to + * keep (AGENTS.md rule 24). This reads both files the way they would, byte for byte, looking for + * text that only the deleted reports carried. + * + *

A file rather than an in-memory database, because the file is the thing being asserted on. + * Its own name, so it never touches the app's real database. + */ +@RunWith(AndroidJUnit4.class) +public class CompactingAfterDeletingHistoryTest { + + private static final String NAME = "compacting-after-deleting-history-test.db"; + private static final String A_TAG = "tag-a"; + + private static final long NOW = 1_800_000_000_000L; + private static final long DAY = TimeUnit.DAYS.toMillis(1); + private static final int A_MONTH = 31; + + /** Only the reports that get deleted carry this. */ + private static final String GONE = "DELETED-REPORT-MARKER"; + /** Only the report that is kept carries this, to show the search can find what is there. */ + private static final String KEPT = "KEPT-REPORT-MARKER"; + + /** Padding, so a few hundred reports fill whole pages rather than share one. */ + private static final String PADDING = "x".repeat(1000); + + private final Context context = getInstrumentation().getTargetContext(); + private OpenTagViewerDatabase db; + private LocationHistoryRetention retention; + + @Before + public void openADatabaseFile() { + this.context.deleteDatabase(NAME); + this.db = Room.databaseBuilder(this.context, OpenTagViewerDatabase.class, NAME) + // As the app has it on any phone with the memory for it. + .setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING) + .allowMainThreadQueries() + .build(); + this.db.ownedBeaconDao().insertAll(OwnedBeacon.builder() + .id(A_TAG) + .content("{}") + .accessoryJson("{\"type\":\"accessory\"}") + .version("0.0.2") + .fromAccount(false) + .isRemoved(false) + .build()); + this.retention = new LocationHistoryRetention(this.db, () -> NOW); + } + + @After + public void deleteIt() { + this.db.close(); + this.context.deleteDatabase(NAME); + } + + @Test + public void choosingAPeriodLeavesNothingOfTheDeletedReportsInTheFile() throws IOException { + this.insertOldReports(300); + this.insertTheNewest(); + assertTrue("the deleted reports were never in the file, so this proves nothing", + this.fileContains(GONE)); + + assertEquals(300, (int) this.retention.prune(A_MONTH).blockingGet()); + + assertTrue("the search cannot find even the report that was kept", + this.fileContains(KEPT)); + assertFalse("a deleted report is still readable in the database file", + this.fileContains(GONE)); + } + + /** + * The delete at every app start only checkpoints, and that alone has to be enough. It is + * here that an unstepped checkpoint, or none, leaves the deleted rows readable. + */ + @Test + public void theDeleteAtStartLeavesNothingOfTheDeletedReportsInTheFile() throws IOException { + this.insertOldReports(300); + this.insertTheNewest(); + assertTrue("the deleted reports were never in the file, so this proves nothing", + this.fileContains(GONE)); + + assertEquals(300, (int) this.retention.pruneAtStart(A_MONTH).blockingGet()); + + assertTrue("the search cannot find even the report that was kept", + this.fileContains(KEPT)); + assertFalse("a deleted report is still readable in the database file", + this.fileContains(GONE)); + } + + private void insertOldReports(final int howMany) { + final LocationReport[] reports = new LocationReport[howMany]; + for (int i = 0; i < howMany; i++) { + reports[i] = report(NOW - (100 * DAY) - i, GONE + "-" + i + "-" + PADDING); + } + this.db.locationReportDao().insertAll(reports); + } + + private void insertTheNewest() { + this.db.locationReportDao().insertAll(report(NOW - DAY, KEPT)); + } + + /** Whether the database file or its write-ahead log holds {@code text}, read as raw bytes. */ + private boolean fileContains(final String text) throws IOException { + final File file = this.context.getDatabasePath(NAME); + final byte[] needle = text.getBytes(StandardCharsets.UTF_8); + return contains(file, needle) || contains(new File(file.getPath() + "-wal"), needle); + } + + private static boolean contains(final File file, final byte[] needle) throws IOException { + if (!file.exists()) { + return false; + } + final byte[] haystack = Files.readAllBytes(file.toPath()); + outer: + for (int i = 0; i + needle.length <= haystack.length; i++) { + for (int j = 0; j < needle.length; j++) { + if (haystack[i + j] != needle[j]) { + continue outer; + } + } + return true; + } + return false; + } + + private static LocationReport report(final long timestamp, final String description) { + return LocationReport.builder() + .hashId(A_TAG + "-" + timestamp) + .beaconId(A_TAG) + .publishedAt(timestamp) + .description(description) + .timestamp(timestamp) + .confidence(1) + .latitude(1.0) + .longitude(-1.0) + .horizontalAccuracy(10L) + .status(0) + .lastUpdate(timestamp) + .provenance(LocationReport.PROVENANCE_APPLE) + .build(); + } +} diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java index 27672141..71ff6684 100644 --- a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/HistoryRetentionSettingTest.java @@ -26,6 +26,8 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import dev.wander.android.opentagviewer.DeviceStateGuard; import dev.wander.android.opentagviewer.Eventually; @@ -37,6 +39,8 @@ import dev.wander.android.opentagviewer.db.repo.UserSettingsRepository; import dev.wander.android.opentagviewer.db.repo.model.UserSettings; import dev.wander.android.opentagviewer.python.AppDependencies; +import dev.wander.android.opentagviewer.ui.TestHostActivity; +import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Single; /** @@ -181,12 +185,55 @@ public void aFailedDeleteKeepsTheNewPeriod() { this.seeSubtitle(R.string.history_retention_1_month); } + /** + * A save that fails deletes nothing, and the screen goes back to the period still stored. + * Hosted on its own so the save can be made to fail without a seam in SettingsActivity. + */ + @Test + public void aFailedSaveDeletesNothingAndPutsThePeriodBack() { + final UserSettings settings = this.repository().getUserSettings(); + final SavesNothing repository = new SavesNothing(); + final AtomicReference subtitle = new AtomicReference<>(); + final String forever = this.context.getString(R.string.history_retention_forever); + + try (ActivityScenario host = + ActivityScenario.launch(TestHostActivity.class)) { + host.onActivity(activity -> { + final HistoryRetentionRow row = + new HistoryRetentionRow(activity, settings, repository, subtitle::set); + row.refresh(); + row.onClick(); + }); + this.pick(R.string.history_retention_1_month); + Eventually.check(() -> onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).check(matches(isDisplayed()))); + onView(withText(R.string.history_retention_confirm_button)) + .inRoot(isDialog()).perform(click()); + + Eventually.check(() -> { + assertEquals(1, repository.attempts.get()); + assertEquals(forever, subtitle.get()); + }); + assertEquals(UserSettings.HISTORY_RETENTION_FOREVER, + settings.resolveHistoryRetentionDays()); + assertEquals("the delete was called although the save failed", + List.of(), this.pruner.storedWhenAsked); + assertEquals(List.of(), this.pruner.asked); + assertEquals(UserSettings.HISTORY_RETENTION_FOREVER, this.storedPeriod()); + } + } + private void open() { this.scenario = ActivityScenario.launch(SettingsActivity.class); } private void choose(final int label) { onView(withId(R.id.settings_history_retention)).perform(scrollTo(), click()); + this.pick(label); + } + + /** Picks {@code label} in the open list of periods and accepts it. */ + private void pick(final int label) { Eventually.check(() -> onView(withText(label)).inRoot(isDialog()) .check(matches(isDisplayed()))); onView(withText(label)).inRoot(isDialog()).perform(click()); @@ -214,16 +261,36 @@ private void storePeriod(final Integer days) { this.repository().storeUserSettings(settings).blockingAwait(); } + /** A settings repository whose every save fails, and which counts the attempts. */ + private final class SavesNothing extends UserSettingsRepository { + final AtomicInteger attempts = new AtomicInteger(); + + SavesNothing() { + super(UserSettingsDataStore.getInstance(HistoryRetentionSettingTest.this.context)); + } + + @Override + public Completable storeUserSettings(final UserSettings userSettings) { + this.attempts.incrementAndGet(); + return Completable.error(new IllegalStateException("a save that fails, on purpose")); + } + } + /** Records each call, and the period stored at that moment. */ private final class RecordingPruner implements HistoryPruner { final List asked = new CopyOnWriteArrayList<>(); final List storedWhenAsked = new CopyOnWriteArrayList<>(); volatile boolean fail = false; + /** + * Records when called, not when subscribed. The real pruner does nothing until + * subscribed, so recording inside the callable could not tell {@code save.andThen(prune)} + * from {@code RxFlows.onlyAfter}: both subscribe once the save is done. + */ @Override public Single prune(final int retentionDays) { + this.storedWhenAsked.add(storedPeriod()); return Single.fromCallable(() -> { - this.storedWhenAsked.add(storedPeriod()); this.asked.add(retentionDays); if (this.fail) { throw new IllegalStateException("a delete that fails, on purpose"); diff --git a/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java b/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java index a6016af8..ae70f15b 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/OpenAirTagApplication.java @@ -140,7 +140,7 @@ private void deleteHistoryOlderThanChosen() { return; } - final int deleted = LocationHistoryRetention.of(this).prune(days).blockingGet(); + final int deleted = LocationHistoryRetention.of(this).pruneAtStart(days).blockingGet(); Log.i(TAG, "Kept " + days + " days of location history; deleted " + deleted + " older reports"); } catch (final Exception e) { diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java index 688cd659..8018c675 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/BeaconRepository.java @@ -2,8 +2,6 @@ import android.util.Log; -import androidx.sqlite.db.SupportSQLiteDatabase; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -1095,7 +1093,7 @@ public Completable removeBeacons( } }); - this.compactBestEffort(); + DatabaseCompaction.now(db, "removing a tag"); }).subscribeOn(Schedulers.io()); } @@ -1110,25 +1108,6 @@ public Completable eraseEverything() { return Completable.fromRunnable(db::clearAllTables).subscribeOn(Schedulers.io()); } - /** - * Rewrite the database file without the free pages a delete leaves behind, then fold the - * write-ahead log back in and truncate it. - * - *

Best effort: if another connection is busy it fails, and the data is still deleted as far - * as the app is concerned - only a forensic reading of the file could find it until the next - * compaction. Not worth failing the user's removal over. - */ - private void compactBestEffort() { - try { - final SupportSQLiteDatabase sqlite = db.getOpenHelper().getWritableDatabase(); - sqlite.execSQL("VACUUM"); - sqlite.query("PRAGMA wal_checkpoint(TRUNCATE)").close(); - } catch (RuntimeException e) { - Log.w(TAG, "Could not compact the database after removing a tag; the rows are gone" - + " but their bytes stay in the file until the next compaction", e); - } - } - public Observable> getInsertionHistoryItem(final String beaconId, final long startOfDayTimestampMS) { return Observable.fromCallable(() -> { DailyHistoryFetchRecord record = db.dailyHistoryFetchRecordDao().getIfExists(beaconId, startOfDayTimestampMS); diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/DatabaseCompaction.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/DatabaseCompaction.java new file mode 100644 index 00000000..a248219a --- /dev/null +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/DatabaseCompaction.java @@ -0,0 +1,77 @@ +package dev.wander.android.opentagviewer.db.repo; + +import android.database.Cursor; +import android.util.Log; + +import androidx.annotation.NonNull; +import androidx.sqlite.db.SupportSQLiteDatabase; + +import dev.wander.android.opentagviewer.db.room.OpenTagViewerDatabase; + +/** + * Makes deleted rows unreadable in the database file, not just in queries. + * + *

Android's SQLite is built with {@code secure_delete} and {@code auto_vacuum} on, so a delete + * zeroes the row and gives freed pages back. That happens in the write-ahead log, though. + * Until a checkpoint, the main file still holds the pages as they were before the delete, and the + * log still holds the frames that wrote the rows in the first place. Anyone reading the files + * directly finds the positions somebody removed or chose not to keep. Measured on the emulator: + * after deleting, the rows are readable in both files; after a checkpoint, in neither. + * + *

The checkpoint has to be stepped. {@code query("PRAGMA wal_checkpoint(TRUNCATE)")} + * returns a cursor that has not run yet; closing it unread runs nothing. That is how this was + * first written, and it left every deleted row in place. {@code CompactingAfterDeletingHistoryTest} + * reads the files byte for byte so that cannot come back quietly. + * + *

Both methods are best effort: if another connection is busy they fail or stop short, and the + * data is still deleted as far as the app is concerned. Not worth failing what the user asked + * for over. The next one finishes the job. + */ +final class DatabaseCompaction { + private static final String TAG = DatabaseCompaction.class.getSimpleName(); + + private DatabaseCompaction() { + } + + /** + * Rewrite the whole file from the live rows, then checkpoint. For deletes somebody asked for: + * a removed tag, a shorter history period. + * + *

The {@code VACUUM} is for a phone whose SQLite does not have {@code secure_delete} on, + * where the checkpoint alone would leave the deleted rows in free space. It rewrites the whole + * file, which is why the delete at every app start does not do it. + */ + static void now(@NonNull final OpenTagViewerDatabase db, @NonNull final String after) { + try { + db.getOpenHelper().getWritableDatabase().execSQL("VACUUM"); + } catch (RuntimeException e) { + Log.w(TAG, "Could not compact the database after " + after, e); + } + checkpoint(db, after); + } + + /** + * Fold the write-ahead log back into the file and truncate it. Cheap: it writes only the + * pages that changed. For the delete at app start. + */ + static void checkpoint(@NonNull final OpenTagViewerDatabase db, @NonNull final String after) { + final SupportSQLiteDatabase sqlite; + try { + sqlite = db.getOpenHelper().getWritableDatabase(); + } catch (RuntimeException e) { + Log.w(TAG, "Could not open the database to checkpoint it after " + after, e); + return; + } + // Read the row: that is what runs it. The first column is 1 when a reader kept it from + // finishing. + try (Cursor result = sqlite.query("PRAGMA wal_checkpoint(TRUNCATE)")) { + if (result.moveToFirst() && result.getInt(0) != 0) { + Log.w(TAG, "The checkpoint after " + after + " could not finish; what was" + + " deleted stays in the write-ahead log until the next one"); + } + } catch (RuntimeException e) { + Log.w(TAG, "Could not checkpoint the database after " + after + "; the rows are" + + " gone but their bytes stay in the files until the next checkpoint", e); + } + } +} diff --git a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java index 3bed677a..cf815c95 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/db/repo/LocationHistoryRetention.java @@ -15,8 +15,10 @@ /** * Deletes location reports older than the period chosen in Settings, keeping each tag's newest. * - *

Runs when the app starts and when a shorter period is chosen. Nothing else deletes history - * on a timer, because the app has no background work outside the optional scan. + *

Runs when the app starts and when a shorter period is chosen, and compacts the file + * afterwards so the deleted reports are not left in it (see {@link DatabaseCompaction}). Nothing + * else deletes history on a timer, because the app has no background work outside the optional + * scan. * *

Keeping everything opens nothing. With the default, {@link #prune} returns without * touching the database, so an install that never chose a period behaves exactly as it did @@ -52,17 +54,45 @@ public static LocationHistoryRetention of(@NonNull final Context context) { System::currentTimeMillis); } + /** + * For a period just chosen in Settings: deletes, then compacts the file if anything went, so + * what was deleted is not still readable in it. See {@link DatabaseCompaction#now}. + */ @Override public Single prune(final int retentionDays) { return Single.fromCallable(() -> { - final long cutoff = cutoffFor(retentionDays, this.clock.getAsLong()); - if (cutoff == NO_CUTOFF) { - return 0; + final int deleted = this.delete(retentionDays); + if (deleted > 0) { + DatabaseCompaction.now(this.db, "deleting older location history"); + } + return deleted; + }).subscribeOn(Schedulers.io()); + } + + /** + * For the delete at app start, which runs every time the app does and removes little each + * time. So it checkpoints rather than rewriting the whole file: that is what clears the + * deleted rows out of the files, and it costs only the pages that changed. See + * {@link DatabaseCompaction#checkpoint}. + */ + public Single pruneAtStart(final int retentionDays) { + return Single.fromCallable(() -> { + final int deleted = this.delete(retentionDays); + if (deleted > 0) { + DatabaseCompaction.checkpoint(this.db, "deleting older location history"); } - return this.db.locationReportDao().deleteOlderThanExceptNewest(cutoff); + return deleted; }).subscribeOn(Schedulers.io()); } + private int delete(final int retentionDays) { + final long cutoff = cutoffFor(retentionDays, this.clock.getAsLong()); + if (cutoff == NO_CUTOFF) { + return 0; + } + return this.db.locationReportDao().deleteOlderThanExceptNewest(cutoff); + } + /** * The oldest report time to keep, in Unix milliseconds, or {@link #NO_CUTOFF}. *