In relational database engineering, there are few error messages as humbling as this one:
android.database.sqlite.SQLiteConstraintException:
FOREIGN KEY constraint failed (code 787 SQLITE_CONSTRAINT_FOREIGNKEY)
It is SQLite's way of telling you: Your deletion order is broken.
During the development of FinLedger's Secret Fund, we implemented a critical privacy feature: 1-Tap Vault Wipe.
If a user ever feels that their device is compromised or simply wants to decommission their private emergency vault, they can tap "Reset & Wipe Vault" in settings. The application should instantly and permanently erase all secret accounts, vault transactions, and transfer bridges from encrypted SQLite.
In our early builds, running this wipe worked fine in basic manual tests.
Then, a beta tester executed a wipe on a vault that had cross-ledger transfers linking an emergency bank account to a public checking account.
The app crashed instantly with error code 787.
Here is how a subtle foreign key constraint violation brought down our vault wipe engine, and how we solved it with deterministic topological deletion ordering (VaultRepository.kt, commit fd19ad0).
The Constraint Crash: What Actually Happened
To understand why SQLite rejected the deletion, examine the relational graph between public tables, vault tables, and cross-ledger bridges:
flowchart TD
subgraph RelationalGraph["The Interconnected Relational Schema"]
PublicAccount["accounts Table (Public)"]
PublicTx["transactions Table (Public)"]
Bridge["vault_transfers Bridge Table:
FK -> transactions.id
FK -> vault_transactions.id"]
VaultAccount["vault_accounts Table (Secret)"]
VaultTx["vault_transactions Table (Secret):
FK -> vault_accounts.id"]
PublicAccount --> PublicTx
PublicTx --> Bridge
VaultAccount --> VaultTx
VaultTx --> Bridge
end
Look at the dependency hierarchy:
-
vault_accountsis the parent ofvault_transactions. -
vault_transactionsis the parent ofvault_transfers. -
transactions(in the public ledger) is also a parent ofvault_transfers.
In our naive pre-audit wipe script, the DAO executed deletion in intuitive human order:
-- The Broken Wipe Sequence
DELETE FROM vault_accounts; -- CRASH! Children still exist in vault_transactions!
DELETE FROM vault_transactions;
DELETE FROM vault_transfers;
Because SQLite was configured with PRAGMA foreign_keys = ON:
- The exact millisecond the engine attempted to delete a row from
vault_accounts, SQLite checked whether child rows existed invault_transactions. - Child rows were present!
- SQLite immediately halted execution, threw error 787, and rolled back the transaction. The vault was not wiped, and the user saw a crash dialog.
The Solution: Deterministic Topological Deletion
In relational graph theory, when deleting a tree of interconnected entities under strict foreign key enforcement, deletion must follow Reverse Topological Order (Leaves $\rightarrow$ Branches $\rightarrow$ Roots):
flowchart TD
subgraph HardenedWipe["The Hardened 4-Step Topological Wipe Pipeline"]
Trigger["User Confirms Vault Wipe"] --> Boundary["Open Atomic SQLite Transaction (withTransaction)"]
Boundary --> Step1["Step 1: Delete Leaf Bridge Entities (vault_transfers)
DELETE FROM vault_transfers WHERE vault_id = :vaultId;
Unlinks all cross-ledger references without breaking public tables."]
Boundary --> Step2["Step 2: Delete Child Records (vault_transactions)
DELETE FROM vault_transactions;
Cleanses all transaction logs, receipts, and category allocations."]
Boundary --> Step3["Step 3: Delete Root Parent Entities (vault_accounts)
DELETE FROM vault_accounts;
Safe! Zero child rows remain in dependent tables."]
Boundary --> Step4["Step 4: Wipe Security Metadata & Preferences
Overwrite stored PIN hashes and geofence anchors with zeros;
Reset VaultSecurityState to UNCONFIGURED."]
Step4 --> Done["Wipe Completed in < 15 ms:
Zero orphaned rows. Zero constraint errors."]
end
Let's examine why this 4-step sequence is mathematically unshakeable:
Step 1: Deleting Leaf Bridges First (vault_transfers)
The cross-ledger bridge table vault_transfers is at the very bottom of the dependency graph.
By deleting rows from vault_transfers first:
- We remove the foreign key link binding vault transactions to public transactions.
- Crucially, the public transactions in the master ledger are not deleted; they simply become unlinked transfer entries.
- The leaf nodes are eliminated, freeing the parent tables from foreign key locks.
Step 2: Deleting Transaction Records (vault_transactions)
Next, all rows in vault_transactions are deleted. Because vault_transfers has already been cleared, no foreign key points to these transactions.
Step 3: Deleting Parent Accounts (vault_accounts)
With vault_transactions completely empty, vault_accounts no longer has any dependent children.
The parent account rows are deleted with zero constraint friction.
Step 4: Cryptographic Key Purge
Finally, once the SQLite tables are empty:
-
SecurityManagerpurges all PBKDF2 hash iterations and salts associated with the vault passcode. - The trusted geofence coordinates are erased.
- The vault transitions to the state
VaultSecurityState.Unconfigured.
The entire 4-step pipeline executes inside Room's database.withTransaction in less than 15 milliseconds.
Testing Wipes in Automated Integration Harnesses
To guarantee that schema migrations and new foreign key additions can never break the wipe pipeline again, we codified the wipe scenario into VaultDatabaseEntityAndMigrationTest.kt:
- Populates the database with multiple vault accounts across all seven archetypes.
- Creates dozens of vault transactions and multiple cross-ledger transfers.
- Triggers the complete wipe pipeline.
- Asserts that the wipe completes with zero exceptions.
- Asserts that querying
vault_accounts,vault_transactions, andvault_transfersreturns a row count of exactly0.
Key Takeaway
Foreign key constraints in SQLite are not an obstacle to be disabled; they are an invariant guard enforcing relational discipline.
When deleting interconnected financial data, intuitive top-down deletion will always lead to constraint crashes. By analyzing entity dependency graphs and enforcing strict reverse topological deletion order, FinLedger guarantees that wiping a confidential vault is instantaneous, complete, and 100% crash-free.
FinLedger is a privacy-first, offline-first personal finance application for Android that models bank accounts, credit cards, and cash without double-counting.
Explore FinLedger on Google Play: https://play.google.com/store/apps/details?id=com.devanshufinance.app

Top comments (1)
Devanshu, the error 787 crash is a great hook for this — and the detail I'd steal is the test asserting exactly 0 rows in all three vault tables after a wipe. That turns the 4-step order from a convention into something provable. Two things your write-up made me think about:
First, step 1 is explicit that the public transactions are not deleted, they just become unlinked entries. But the test you describe only asserts the three vault tables hit 0. Do you also assert the public ledger's row count is unchanged after a wipe? That is the regression the reverse-topological order is really guarding: a future edit that cleared transfers and took the public rows with them would still pass the 0-rows check.
Second, step 4 — purging the PBKDF2 salts and moving to VaultSecurityState.Unconfigured — happens once the tables are empty. Is that purge inside the same withTransaction as the deletes, or after it commits? If the app is killed in the gap between commit and purge, you get an empty vault with live keys, which is harmless; the reverse order (keys first, crash before the wipe) would leave data no key can open. Your ordering already picks the safe failure mode — I'm curious whether the 15 ms figure holds at the scale a long-time user accumulates, where the write lock is held a lot longer than for dozens of transactions. Have you run the wipe against a vault with thousands of transactions yet?