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 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 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