Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

/**
Expand Down Expand Up @@ -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<String> subtitle = new AtomicReference<>();
final String forever = this.context.getString(R.string.history_retention_forever);

try (ActivityScenario<TestHostActivity> 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());
Expand Down Expand Up @@ -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<Integer> asked = new CopyOnWriteArrayList<>();
final List<Integer> 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<Integer> 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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1095,7 +1093,7 @@ public Completable removeBeacons(
}
});

this.compactBestEffort();
DatabaseCompaction.now(db, "removing a tag");
}).subscribeOn(Schedulers.io());
}

Expand All @@ -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.
*
* <p>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<Optional<DailyHistoryFetchRecord>> getInsertionHistoryItem(final String beaconId, final long startOfDayTimestampMS) {
return Observable.fromCallable(() -> {
DailyHistoryFetchRecord record = db.dailyHistoryFetchRecordDao().getIfExists(beaconId, startOfDayTimestampMS);
Expand Down
Loading