test: the version the app ships, opened by the version it builds (marmot-kmp, Phase 9)

Phase 4 settled the blob and left the database alone, because there was nothing
to settle: the state is opaque to Room and its version is inside it. Phase 8 added
a table, and that turns "does an existing install still open?" from a question
about MLS into a question about Room. They fail differently. A blob the engine
cannot read costs one room; a migration Room cannot find costs the app, on every
device that has ever had it, on the first launch after the update.

That second one is also the easiest here to ship by accident, because a fresh
install never migrates anything. Measured rather than assumed: with
`AutoMigration(from = 36, to = 37)` commented out, 32 database tests ran and 4
failed -- all four of them the new ones.

ShippedProfileUpgradeJvmTest builds a v36 database on disk from the exported v36
schema, down to its indices, its room_master_table identity hash and its
user_version, puts a profile and two rooms in it with the Phase 4 blob in one, and
opens it with the app's own getRoomDatabase. Four claims: it reaches v37 with
Room's own identity hash stamped and every table's columns and indices equal to
37.json's; the legacy room's bytes come back unchanged and MarmotEngine.groupFor
restores a group with its 0xF2EE metadata and a 32-byte kind:445 key; opening the
profile rewrites nothing, which is asserted only after checking the restore held
the room; and the new table takes a row keyed to a ChatRoom that predates it.

Room opens lazily, so a test that builds a database and closes it migrates
nothing. The first version of this did that and failed on user_version still
reading 36.

The blob itself moves to OldEngineBlob in commonTest, read by both tests. The
only thing those bytes are worth is that they are old ones, and a blob living in
two files can be regenerated in one of them.

1171 tests across 157 classes, 0 failures; the four audits unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5 committed 2026-11-19 18:57:12 +02:00
1 parent e07bb68014
commit 1321962b3f
7 files changed
+538 -80

No files matched your search

@@ -28,14 +28,15 @@ import mobi.giza.compose.extensions.exporterSecret
*
* The argument that it holds is good: the blob's first field is a `uint16` version,
* quartz 1.15.2 wrote `STATE_VERSION = 4`, mls-kmp 1.3.0 accepts `1..10`, and its comments
* say each version only appends. But an argument is not a measurement, and the blob below
* say each version only appends. But an argument is not a measurement, and [OldEngineBlob]
* is the measurement: real bytes from the old engine, generated by a throwaway project
* with `com.vitorpamplona.quartz:quartz:1.15.2` as its only dependency, pinned here so
* that the day a future mls-kmp stops reading version 4, this test says so rather than a
* with `com.vitorpamplona.quartz:quartz:1.15.2` as its only dependency, pinned so that
* the day a future mls-kmp stops reading version 4, this test says so rather than a
* user's phone.
*
* It is a legacy MIP-01 group at epoch 0, which is the shape every room in the wild
* started as. docs/marmot-kmp.md, Phase 4.
* This is the blob on its own. `ShippedProfileUpgradeJvmTest` is the same bytes in a
* database at the version the app shipped, opened by this branch -- the other half of
* the same constraint. docs/marmot-kmp.md, Phases 4 and 9.
*/
class MlsGroupStateCompatibilityTest {
@@ -46,11 +47,10 @@ class MlsGroupStateCompatibilityTest {
*/
@Test
fun `the fixture is a blob the old engine wrote, at its state version`() {
val bytes = OLD_ENGINE_BLOB.hexToByteArray()
val version = (bytes[0].toInt() and 0xff shl 8) or (bytes[1].toInt() and 0xff)
val bytes = OldEngineBlob.HEX.hexToByteArray()
assertEquals(
OLD_ENGINE_STATE_VERSION,
version,
OldEngineBlob.STATE_VERSION,
OldEngineBlob.stateVersionOf(bytes),
"the fixture is no longer a blob quartz 1.15.2 would have written",
)
}
@@ -58,7 +58,7 @@ class MlsGroupStateCompatibilityTest {
/** It decodes, and it still says what it said. */
@Test
fun `mls-kmp decodes it and keeps what it said`() {
val state = MlsGroupState.decodeTls(OLD_ENGINE_BLOB.hexToByteArray())
val state = MlsGroupState.decodeTls(OldEngineBlob.HEX.hexToByteArray())
assertEquals(0L, state.groupContext.epoch, "epoch moved in the decode")
assertEquals(0, state.myLeafIndex, "the creator is no longer leaf 0")
@@ -72,11 +72,11 @@ class MlsGroupStateCompatibilityTest {
*/
@Test
fun `the group restores from it with its metadata intact`() {
val group = MlsGroup.restore(MlsGroupState.decodeTls(OLD_ENGINE_BLOB.hexToByteArray()), MarmotGroupPolicy)
val group = MlsGroup.restore(MlsGroupState.decodeTls(OldEngineBlob.HEX.hexToByteArray()), MarmotGroupPolicy)
assertTrue(group.isLocalMember(), "the restored group does not hold us")
val data = assertNotNull(group.currentMarmotData(), "the 0xF2EE extension did not survive")
assertEquals(OLD_ENGINE_ROOM_ID, data.nostrGroupId, "the room's address changed")
assertEquals(OldEngineBlob.ROOM_ID, data.nostrGroupId, "the room's address changed")
assertEquals("Fixture", data.name, "the group's name changed")
assertTrue(group.currentGroupState().isCurrentProfile.not(), "a legacy group read as current-profile")
}
@@ -90,7 +90,7 @@ class MlsGroupStateCompatibilityTest {
*/
@Test
fun `the outer kind445 key is derivable from a restored old group`() {
val group = MlsGroup.restore(MlsGroupState.decodeTls(OLD_ENGINE_BLOB.hexToByteArray()), MarmotGroupPolicy)
val group = MlsGroup.restore(MlsGroupState.decodeTls(OldEngineBlob.HEX.hexToByteArray()), MarmotGroupPolicy)
assertEquals(32, group.exporterSecret().size, "the group-event exporter secret is the wrong length")
}
@@ -101,12 +101,12 @@ class MlsGroupStateCompatibilityTest {
*/
@Test
fun `a re-save moves it to the current version and still decodes`() {
val group = MlsGroup.restore(MlsGroupState.decodeTls(OLD_ENGINE_BLOB.hexToByteArray()), MarmotGroupPolicy)
val group = MlsGroup.restore(MlsGroupState.decodeTls(OldEngineBlob.HEX.hexToByteArray()), MarmotGroupPolicy)
val resaved = group.saveState().encodeTls()
val version = (resaved[0].toInt() and 0xff shl 8) or (resaved[1].toInt() and 0xff)
val version = OldEngineBlob.stateVersionOf(resaved)
assertTrue(
version > OLD_ENGINE_STATE_VERSION,
version > OldEngineBlob.STATE_VERSION,
"a re-save did not move the blob forward: version $version",
)
@@ -114,7 +114,7 @@ class MlsGroupStateCompatibilityTest {
assertEquals(0L, again.groupContext.epoch)
assertEquals(0, again.myLeafIndex)
assertContentEquals(
MlsGroupState.decodeTls(OLD_ENGINE_BLOB.hexToByteArray()).groupContext.groupId,
MlsGroupState.decodeTls(OldEngineBlob.HEX.hexToByteArray()).groupContext.groupId,
again.groupContext.groupId,
"the group id changed across a re-save",
)
@@ -146,42 +146,4 @@ class MlsGroupStateCompatibilityTest {
assertEquals(3, back.leafCount)
assertContentEquals(retained.exporterSecret, back.exporterSecret)
}
companion object {
/** What quartz 1.15.2's `MlsGroupState.STATE_VERSION` was. */
private const val OLD_ENGINE_STATE_VERSION = 4
/** The `nostr_group_id` in the fixture's MIP-01 extension. */
private const val OLD_ENGINE_ROOM_ID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
/**
* `MlsGroup.create(identity, null, listOf(MarmotGroupData.bootstrap(...).toExtension()))`
* under quartz 1.15.2, saved and TLS-encoded. Regenerate with the project in
* docs/marmot-kmp.md, Phase 4, if it ever needs to be a different shape; do not
* regenerate it with the new engine, which would defeat the point.
*/
private const val OLD_ENGINE_BLOB =
"00040001000120c3c9d291c98d1f3f01dabcdcf2abf99980ae06e9631539e4f7e5b547ad2c03dc000000000000000020" +
"b675ae4d9e4062d1dafbf3d3b4dc67e98063def6dbda2008f60573c200ae6d5b0040a600030902f2ee02000a020001f2" +
"ee40960002aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa07466978747572652d4120" +
"6c6567616379204d49502d303120726f6f6d207772697474656e2062792071756172747a20312e31352e322000749390" +
"d99f65603651fbf8baf7071ad63ee5660984958d1dd7a5821c92b52a18177773733a2f2f72656c61792e6578616d706c" +
"652e636f6d0000000040cc40ca010120b9da1a21fffe43be2a5e2b83eddc853f71f6b57fae67e017be8dbfb1778ce95f" +
"209b4ebc94792d7360f4017d45cbd845e5f488e4962754239af9d48de50ea5224900012000749390d99f65603651fbf8" +
"baf7071ad63ee5660984958d1dd7a5821c92b52a02000102000102f2ee02000a02000101000000006afe12c000000000" +
"6b6cd0c0004040ca7ad7d4a33a7cbde134f8225938ea6a1e65cd06379b71abb00ab48fe17935712db23a56630d92c7c5" +
"4cea6a3eb62326a3228e7464820518e9cda1923d50a80000000000209e5c0c64ef40fead8259db9426c4af2bec91f750" +
"c5a0b6c767ccc431cf6e2c412087f4d7255d2a5126cb5c0a8d794a335f0d0032e66555546904405be0f216b371208ae2" +
"411f07faac6dae2f701e5c6e8a7e36255f7dc91565e5faaf58b74905b80d2041e6e1452c80b6d6ed44e1a3d320478af4" +
"6daa55a05e4b5edf833b28219d4730200e4f86c223b2113e0691b2094155e2623fdf6030e08f293cd05da34122c62b54" +
"20337d8cf084bab81304c588ebbb8309571165cd0f1b6ddfdfbdbd0a0d7df7998c20528a63ffcf11b677324646bfb478" +
"b89a896cc40105e5ff91b9d23a9a1e4d4fba2096d23998acca0e6575649594539dee4101ddd9a5e9e9d9995db290eaba" +
"e7878e204888d7a4c9cacfedec6299d6a503055615e5824cc09e90ffe865cbd497310b1320c25e0955cf5a866ae44b5f" +
"698569fa427455e4a74187f69b4fc9d3e4badceaea2052371f31ed9069072037b2ea4ea312f34adb27601ece5a6fee29" +
"68fb8656e9522074a9d547eaf3b009f58a0b647cbee2947800db888f4e9fa3d9c9add7460d03de2074a9d547eaf3b009" +
"f58a0b647cbee2947800db888f4e9fa3d9c9add7460d03de4040331d4cde98587d393b9bd906ad826fd40e0ec3bd33e0" +
"23aac8c223bd7c6cba859b4ebc94792d7360f4017d45cbd845e5f488e4962754239af9d48de50ea5224920df018d4154" +
"497d07c9363f4ada26d4a68d0eb7f77ccd837ccb6540b76148571700200e4f86c223b2113e0691b2094155e2623fdf60" +
"30e08f293cd05da34122c62b54000000000000000000000000"
}
}
@@ -0,0 +1,57 @@
package mobi.giza.compose.managers
/**
* One group state blob, written by the engine the app shipped before it moved to
* marmot-kmp, with the two facts a test needs in order to know it is still that blob.
*
* It sits here rather than inside the test that first used it because two tests now
* depend on these bytes being *old* ones: [MlsGroupStateCompatibilityTest], which
* decodes them with mls-kmp, and `ShippedProfileUpgradeJvmTest`, which puts them in a
* v36 database and opens that database with this branch. A blob copied into two files
* can be regenerated in one of them, and the copy that was left alone would then be
* the only evidence, with nothing on either saying which was which.
*
* Regenerate with the project in docs/tools/old-state-blob, whose only dependency is
* `com.vitorpamplona.quartz:quartz:1.15.2` -- never with the engine the app now
* ships, which would leave every test over it passing and measuring nothing.
*
* docs/marmot-kmp.md, Phases 4 and 9.
*/
internal object OldEngineBlob {
/** What quartz 1.15.2's `MlsGroupState.STATE_VERSION` was. */
const val STATE_VERSION = 4
/** The `nostr_group_id` in the fixture's MIP-01 extension, and the room's id. */
const val ROOM_ID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
/**
* `MlsGroup.create(identity, null, listOf(MarmotGroupData.bootstrap(...).toExtension()))`
* under quartz 1.15.2, saved and TLS-encoded: a legacy MIP-01 group at epoch 0,
* which is the shape every room in the wild started as.
*/
const val HEX =
"00040001000120c3c9d291c98d1f3f01dabcdcf2abf99980ae06e9631539e4f7e5b547ad2c03dc000000000000000020b675" +
"ae4d9e4062d1dafbf3d3b4dc67e98063def6dbda2008f60573c200ae6d5b0040a600030902f2ee02000a020001f2ee409600" +
"02aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa07466978747572652d41206c6567616379" +
"204d49502d303120726f6f6d207772697474656e2062792071756172747a20312e31352e322000749390d99f65603651fbf8" +
"baf7071ad63ee5660984958d1dd7a5821c92b52a18177773733a2f2f72656c61792e6578616d706c652e636f6d0000000040" +
"cc40ca010120b9da1a21fffe43be2a5e2b83eddc853f71f6b57fae67e017be8dbfb1778ce95f209b4ebc94792d7360f4017d" +
"45cbd845e5f488e4962754239af9d48de50ea5224900012000749390d99f65603651fbf8baf7071ad63ee5660984958d1dd7" +
"a5821c92b52a02000102000102f2ee02000a02000101000000006afe12c0000000006b6cd0c0004040ca7ad7d4a33a7cbde1" +
"34f8225938ea6a1e65cd06379b71abb00ab48fe17935712db23a56630d92c7c54cea6a3eb62326a3228e7464820518e9cda1" +
"923d50a80000000000209e5c0c64ef40fead8259db9426c4af2bec91f750c5a0b6c767ccc431cf6e2c412087f4d7255d2a51" +
"26cb5c0a8d794a335f0d0032e66555546904405be0f216b371208ae2411f07faac6dae2f701e5c6e8a7e36255f7dc91565e5" +
"faaf58b74905b80d2041e6e1452c80b6d6ed44e1a3d320478af46daa55a05e4b5edf833b28219d4730200e4f86c223b2113e" +
"0691b2094155e2623fdf6030e08f293cd05da34122c62b5420337d8cf084bab81304c588ebbb8309571165cd0f1b6ddfdfbd" +
"bd0a0d7df7998c20528a63ffcf11b677324646bfb478b89a896cc40105e5ff91b9d23a9a1e4d4fba2096d23998acca0e6575" +
"649594539dee4101ddd9a5e9e9d9995db290eabae7878e204888d7a4c9cacfedec6299d6a503055615e5824cc09e90ffe865" +
"cbd497310b1320c25e0955cf5a866ae44b5f698569fa427455e4a74187f69b4fc9d3e4badceaea2052371f31ed9069072037" +
"b2ea4ea312f34adb27601ece5a6fee2968fb8656e9522074a9d547eaf3b009f58a0b647cbee2947800db888f4e9fa3d9c9ad" +
"d7460d03de2074a9d547eaf3b009f58a0b647cbee2947800db888f4e9fa3d9c9add7460d03de4040331d4cde98587d393b9b" +
"d906ad826fd40e0ec3bd33e023aac8c223bd7c6cba859b4ebc94792d7360f4017d45cbd845e5f488e4962754239af9d48de5" +
"0ea5224920df018d4154497d07c9363f4ada26d4a68d0eb7f77ccd837ccb6540b76148571700200e4f86c223b2113e0691b2" +
"094155e2623fdf6030e08f293cd05da34122c62b54000000000000000000000000"
/** The first two bytes of [HEX], which are the state version. */
fun stateVersionOf(bytes: ByteArray): Int = (bytes[0].toInt() and 0xff shl 8) or (bytes[1].toInt() and 0xff)
}
@@ -0,0 +1,361 @@
package mobi.giza.compose.database.migrations
import androidx.room3.Room
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import androidx.sqlite.execSQL
import com.vitorpamplona.marmot.groups.currentMarmotData
import java.io.File
import java.nio.file.Files
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.MarmotSenderRatchet
import mobi.giza.compose.extensions.exporterSecret
import mobi.giza.compose.managers.OldEngineBlob
/**
* A profile written by the app as it ships, opened by the app as this branch builds it.
*
* `MlsGroupStateCompatibilityTest` is the blob on its own: bytes quartz 1.15.2 wrote,
* handed straight to mls-kmp. This is the same bytes where a user's are -- in a
* database at schema 36, which is what every install on the `giza` branch is at -- and
* the thing being opened is the app's own `GizaDatabase`, through the builder the app
* uses, rather than a decoder in a test. Phase 8 added a table, so this branch is the
* first in a while whose upgrade can fail for a reason that has nothing to do with MLS.
*
* It is named for what it opens rather than for a migration, because 36 -> 37 is an
* `AutoMigration` and there is no `MIGRATION_36_37` to call: Room generates it, and
* the only way to run the generated one is to let Room decide it is needed. That is
* also the failure this catches. An entity added to the `@Database` list without an
* `AutoMigration` beside it builds, passes every test over an in-memory database, and
* installs perfectly on a phone that has never had the app -- and throws
* `IllegalStateException: A migration from 36 to 37 was required but not found` on
* every phone that has.
*
* The v36 database is built from the exported schema rather than from copied SQL, so
* its tables, indices and identity hash are exactly a v36 install's, which is the same
* argument `RemoveWalletsMigrationJvmTest` makes one version earlier.
*
* What it does not cover is a real profile's accumulated rows, and where the file sits:
* `PlatformDatabaseBuilder` picks the path per target and this picks a temporary one.
* The engine under it is the same everywhere -- `getRoomDatabase` sets
* `BundledSQLiteDriver()` in common code, so Android, iOS and desktop all migrate
* through the SQLite this test migrates through. docs/marmot-kmp.md, Phase 9.
*/
class ShippedProfileUpgradeJvmTest {
/** The schema version on `giza`, which is the one every existing install is at. */
private val shipped = 36
/** The schema version this branch builds. */
private val current = 37
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")
@AfterTest
fun cleanUp() {
directory.deleteRecursively()
}
private val schemas: File =
(File("schemas").takeIf { it.isDirectory } ?: File("composeApp/schemas"))
.resolve("mobi.giza.compose.database.GizaDatabase")
private fun schema(version: Int): JsonObject =
Json.parseToJsonElement(schemas.resolve("$version.json").readText())
.jsonObject["database"]!!.jsonObject
private fun entities(version: Int): List<JsonObject> =
schema(version)["entities"]!!.jsonArray.map { it.jsonObject }
private fun JsonObject.tableName() = this["tableName"]!!.jsonPrimitive.content
private fun JsonObject.columns() =
this["fields"]!!.jsonArray.map { it.jsonObject["columnName"]!!.jsonPrimitive.content }.toSet()
private fun JsonObject.indexNames() =
this["indices"]?.jsonArray.orEmpty().map { it.jsonObject["name"]!!.jsonPrimitive.content }.toSet()
// -- the v36 profile -------------------------------------------------------------
private val userPublicKey = "f".repeat(64)
private val profileEventId = "e".repeat(64)
/** A room with no MLS state of its own, so the engine has to pick between two. */
private val plainRoomId = "b".repeat(64)
/**
* The database a v36 install has: its own schema, its own `room_master_table`
* identity hash and its own `user_version`, which together are what make Room
* treat the file as a v36 database rather than a corrupt one.
*/
private fun writeShippedProfile() {
BundledSQLiteDriver().open(file.absolutePath).use { connection ->
entities(shipped).forEach { entity ->
val table = entity.tableName()
connection.execSQL(entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table))
entity["indices"]?.jsonArray.orEmpty().forEach { index ->
connection.execSQL(index.jsonObject["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table))
}
}
schema(shipped)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) }
connection.execSQL("PRAGMA user_version = $shipped")
insert(connection, "NostrEvent", mapOf("id" to profileEventId, "pubKey" to userPublicKey))
insert(connection, "Profile", mapOf("publicKey" to userPublicKey, "nostrEventId" to profileEventId))
insert(
connection,
"ChatRoom",
mapOf(
"id" to OldEngineBlob.ROOM_ID,
"userPublicKey" to userPublicKey,
"subject" to "Fixture",
"mlsGroupState" to OldEngineBlob.HEX,
),
)
insert(
connection,
"ChatRoom",
mapOf("id" to plainRoomId, "userPublicKey" to userPublicKey, "mlsGroupState" to null),
)
}
}
/**
* A row in [table] carrying [values], every other NOT NULL column without a default
* given a placeholder of its affinity. Bound rather than interpolated, so a BLOB
* column gets bytes instead of the text of a number.
*/
private fun insert(connection: SQLiteConnection, table: String, values: Map<String, Any?>) {
val entity = entities(shipped).single { it.tableName() == table }
val filled = LinkedHashMap<String, Any?>()
entity["fields"]!!.jsonArray.map { it.jsonObject }.forEach { field ->
val column = field["columnName"]!!.jsonPrimitive.content
val notNull = field["notNull"]?.jsonPrimitive?.booleanOrNull == true
val hasDefault = field["defaultValue"] != null
when {
column in values -> filled[column] = values[column]
notNull && !hasDefault -> filled[column] = when (field["affinity"]!!.jsonPrimitive.content) {
"TEXT" -> "x"
"BLOB" -> ByteArray(0)
else -> 1L
}
}
}
val sql = "INSERT INTO `$table` (${filled.keys.joinToString(", ") { "`$it`" }}) " +
"VALUES (${filled.keys.joinToString(", ") { "?" }})"
connection.prepare(sql).use { statement ->
filled.values.forEachIndexed { position, value ->
val index = position + 1
when (value) {
null -> statement.bindNull(index)
is String -> statement.bindText(index, value)
is ByteArray -> statement.bindBlob(index, value)
is Long -> statement.bindLong(index, value)
is Int -> statement.bindLong(index, value.toLong())
else -> error("no binding for a ${value::class.simpleName}")
}
}
statement.step()
}
}
// -- opening it ------------------------------------------------------------------
/**
* The app's own builder over that file -- the migrations the app ships, and no
* others -- opened, used and closed.
*
* Room opens lazily: `build()` returns a database that has not touched the file,
* and the migration runs on the first query. So [use] has to ask it something, and
* a test that only built and closed one would pass against a file nothing had
* migrated.
*/
private suspend fun <T> opened(use: suspend (GizaDatabase) -> T): T {
val database = getRoomDatabase(Room.databaseBuilder<GizaDatabase>(name = file.absolutePath))
return try {
use(database)
} finally {
database.close()
}
}
private fun <T> onDisk(read: (SQLiteConnection) -> T): T =
BundledSQLiteDriver().open(file.absolutePath).use(read)
private fun SQLiteConnection.tables(): Set<String> =
prepare("SELECT name FROM sqlite_master WHERE type = 'table'").use { statement ->
buildSet { while (statement.step()) add(statement.getText(0)) }
}.filterNot { it.startsWith("sqlite_") || it == "room_master_table" }.toSet()
private fun SQLiteConnection.columnsOf(table: String): Set<String> =
prepare("PRAGMA table_info(`$table`)").use { statement ->
buildSet { while (statement.step()) add(statement.getText(1)) }
}
private fun SQLiteConnection.indexNamesOf(table: String): Set<String> =
prepare("PRAGMA index_list(`$table`)").use { statement ->
buildSet { while (statement.step()) add(statement.getText(1)) }
}.filter { it.startsWith("index_") }.toSet()
private fun SQLiteConnection.userVersion(): Long =
prepare("PRAGMA user_version").use { statement -> statement.step(); statement.getLong(0) }
private fun SQLiteConnection.identityHash(): String =
prepare("SELECT identity_hash FROM room_master_table WHERE id = 42").use { statement ->
statement.step()
statement.getText(0)
}
// -- what it has to prove --------------------------------------------------------
/**
* Room finds the way from 36 to 37, runs it, and stamps the file with the hash the
* generated code expects. The hash is the assertion that matters: Room writes it
* only after `validateMigration` has compared every table it was handed against the
* schema the entities declare.
*/
@Test
fun `a v36 profile opens at v37, with the table this branch adds`(): Unit = runBlocking {
writeShippedProfile()
onDisk { connection ->
assertEquals(shipped.toLong(), connection.userVersion(), "the fixture is not at the shipped version")
assertTrue("MarmotSenderRatchet" !in connection.tables(), "the fixture already has the new table")
}
opened { database ->
assertTrue(database.chatRoomDao().exists(OldEngineBlob.ROOM_ID), "the room is gone after the upgrade")
}
onDisk { connection ->
assertEquals(current.toLong(), connection.userVersion(), "the file was not moved to the new version")
assertEquals(
schema(current)["identityHash"]!!.jsonPrimitive.content,
connection.identityHash(),
"Room did not stamp the v37 identity hash, so it did not validate the migrated schema",
)
val expected = entities(current).associateBy { it.tableName() }
assertEquals(expected.keys, connection.tables(), "the migrated file has a different set of tables")
expected.forEach { (table, entity) ->
assertEquals(entity.columns(), connection.columnsOf(table), "the columns of $table")
assertEquals(entity.indexNames(), connection.indexNamesOf(table), "the indices of $table")
}
}
}
/**
* And the room in it is still a room. The blob is read back out of the migrated
* file, restored by the engine that replaced the one that wrote it, and asked for
* the two things the app needs from a group before it can show a message: the
* MIP-01 metadata, and the exporter secret the kind:445 wrapper is sealed with.
*/
@Test
fun `the legacy room survives the upgrade and the engine opens it`(): Unit = runBlocking {
writeShippedProfile()
opened { database ->
assertEquals(
OldEngineBlob.HEX,
database.chatRoomDao().getMlsGroupState(OldEngineBlob.ROOM_ID),
"the room's state is not the bytes that were in the file",
)
val group = assertNotNull(
database.marmotEngine.groupFor(OldEngineBlob.ROOM_ID),
"the engine holds no group for a room that has state on disk",
)
val data = assertNotNull(group.currentMarmotData(), "the 0xF2EE extension did not survive the upgrade")
assertEquals(OldEngineBlob.ROOM_ID, data.nostrGroupId, "the room's address changed")
assertEquals(32, group.exporterSecret().size, "the group-event exporter secret is the wrong length")
assertNull(
database.marmotEngine.groupFor(plainRoomId),
"a room with no state came back with a group",
)
}
}
/**
* An upgrade does not rewrite the rooms it finds.
*
* Restoring a group re-derives its key schedule and could just as well save the
* result at the current state version, and the first thing that persists each room
* will do exactly that (`MlsGroupStateCompatibilityTest` is that re-save on its
* own). Doing it to every room at once, on the first launch after an upgrade, is a
* different thing: it is the one moment when every room's only copy is being
* rewritten, and a crash in the middle of it has no floor under it. So the claim
* here is the absence of a write.
*/
@Test
fun `opening the profile leaves the rooms it restored as they were`(): Unit = runBlocking {
writeShippedProfile()
opened { database ->
database.marmotEngine.ensureRestored()
// Without this the test asserts the absence of a write by an engine that
// may be holding nothing: `groupFor` would load the room from its row on
// demand, so only the restore itself proves the room was picked up.
assertNotNull(
database.marmotEngine.groupManager.snapshot(OldEngineBlob.ROOM_ID),
"the restore did not pick the room up, so there is no write for this test to be about",
)
}
onDisk { connection ->
val stored = connection.prepare("SELECT mlsGroupState FROM ChatRoom WHERE id = ?").use { statement ->
statement.bindText(1, OldEngineBlob.ROOM_ID)
statement.step()
statement.getText(0)
}
assertEquals(
OldEngineBlob.HEX,
stored,
"a restore rewrote the room's state; the bytes on disk are no longer the ones quartz 1.15.2 wrote",
)
}
}
/**
* The new table's foreign key points at `ChatRoom`, which is a table that was
* already there with rows in it -- the one direction an added table can be wrong
* in. A row keyed to a room that predates the table has to be insertable, and
* readable back.
*/
@Test
fun `the added table takes a row keyed to a room that predates it`(): Unit = runBlocking {
writeShippedProfile()
opened { database ->
val dao = database.marmotSenderRatchetDao()
assertNull(dao.forChatRoomId(OldEngineBlob.ROOM_ID), "the new table arrived with a row in it")
dao.upsert(
MarmotSenderRatchet(
chatRoomId = OldEngineBlob.ROOM_ID,
epoch = 0L,
leafIndex = 0,
applicationGeneration = 0,
record = ByteArray(8) { it.toByte() },
)
)
val row = assertNotNull(dao.forChatRoomId(OldEngineBlob.ROOM_ID), "the row did not come back")
assertContentEquals(ByteArray(8) { it.toByte() }, row.record, "the record came back as different bytes")
}
}
}
+10 -9
View File
@@ -31,7 +31,7 @@ the [retired](./retired/) notes now.
| [npub-profile-preview.md](./npub-profile-preview.md) | showing the person before a direct message is started from a pasted npub — why the preview is a screen keyed by public key, what "found" means when a row can be a placeholder, and the phase that makes the button honest about a key package that never comes |
| [material-design-conformance.md](./material-design-conformance.md) | what the M3 foundations actually require, measured against all 43 screens — the colour pairing that renders the app's own proposals invisible, and eight phases that put the decisions back in the theme |
| [marmot-v2.md](./marmot-v2.md) | bringing the group layer onto the Marmot current profile after the quartz 1.15.2 bump — the nine rules that reach this app, why the room's id and the routing id have to become two values, nine phases from reading both profiles to publishing before applying, and the one fork the library cannot yet settle |
| [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, and how often this app persists a group once a sent message no longer rewrites it |
| [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships |
| [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase |
| [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu |
@@ -81,19 +81,20 @@ of nine rules and its two constraints before any phase, and its table of where t
build chose differently before any of the code -- its first row, that a room's
profile picks its pipeline, is the shape of everything that follows, and its last
is the one fork the library cannot yet settle.
The marmot-kmp note is a phased plan that has been built, phases 0 to 8, and reads
The marmot-kmp note is a phased plan that has been built, phases 0 to 9, and reads
as the Marmot v2 note's Phase 0 come round again: quartz took the engine out, so
the version the v2 work was built on is the last one that has it. Read the v2 note
first — this plan happens entirely on the current-profile side of its first row —
and read this one's two constraints before any phase: the group state already on
devices is what decides whether the move can ship at all, and Phase 4 is where it
is measured rather than argued. Phase 8 is the one phase that was not in the plan
as written, and is the one to read if you are changing when a group is saved: it
is where a sent message stopped rewriting the whole state, where the ordering that
decision hangs on is spelled out, and where the skipped-keys note's diagnosis is
corrected. What it does not claim is in its status note: no manual upgrade of a
profile with real rooms has been done, and that is the last check before a release,
now over a schema change as well.
is measured rather than argued. Phases 8 and 9 were not in the plan as written and
are the pair to read if you are changing when a group is saved or what the database
holds: 8 is where a sent message stopped rewriting the whole state, where the
ordering that decision hangs on is spelled out, and where the skipped-keys note's
diagnosis is corrected; 9 is the schema change 8 made necessary, opened from a
database at the version the app ships. What they do not claim is in the status note:
no manual upgrade of a profile with rooms that have real histories has been done, and
that is still the last check before a release.
The ceremony-creation note is a phased plan that has been built. It reads as
the subgroups note's Phase 10 followed through to the screens: read it after
that phase, and its table of findings before any phase. Its second half
+76 -7
View File
@@ -20,18 +20,19 @@ everything here happens on the current-profile side of that branch.
[mls-skipped-keys.md](./mls-skipped-keys.md) second — it is the gap this move closes, and
the only one it closes for free.
**Built**, phases 0 to 8, one commit each but for 5 and 6, which share one because the
fork probe produced no code. Phase 8 was the piece Phase 7 deferred and is the only one
that was not in the plan as written. Written against the code as it stood at `8b066795`,
**Built**, phases 0 to 9, one commit each but for 5 and 6, which share one because the
fork probe produced no code. Phases 8 and 9 were not in the plan as written: 8 is the
piece Phase 7 deferred, and 9 is the schema change 8 made necessary, checked. Written against the code as it stood at `8b066795`,
against marmot-kmp `2.2.1`, mls-kmp `1.3.0`, crypto-kmp `2.1.0` and quartz `2.7.3`. The
phases are kept as they were written, with what each one turned out to be recorded under
it, because the reasoning is the point and the code reads better against the argument it
came from.
Two things it does not claim. **The manual upgrade has not been done** — Phase 4 proves a
real version-4 blob opens, and a profile with real rooms in it is still the last check
before a release, now over a schema change as well (36 → 37). **And the authored fork is
still not settled** — Phase 6 probed it and the gap is the library's, unchanged.
real version-4 blob opens and Phase 9 proves a v36 database carrying one opens at v37, but
a profile with rooms that have real histories in them is still the last check before a
release. **And the authored fork is still not settled** — Phase 6 probed it and the gap is
the library's, unchanged.
| phase | what it was |
|---|---|
@@ -44,6 +45,7 @@ still not settled** — Phase 6 probed it and the gap is the library's, unchange
| 6 | the authored fork, probed: still open, and the fix now visible |
| 7 | the guard, so the engine cannot come back from quartz |
| 8 | the sender ratchet as its own row, and the receive-side write beside it |
| 9 | the schema change that followed, opened from the version the app ships |
## Where the engine went
@@ -453,7 +455,9 @@ is inside it, and schema 36 stands.
group at epoch 0 with one member. The rooms that matter have been through several epochs,
several members and a retained-epoch window, and the only way to know they open is to open
one. That check needs a device or desktop profile with real rooms in it, and it is the last
thing between this work and a release.
thing between this work and a release. Phase 9 takes half of it: the *database* a v36
install has, opened at v37 with this blob inside it, is a test now. The histories in a real
profile still are not.
## Phase 5 — the skipped keys, closed
@@ -736,6 +740,71 @@ secrets, so it is exactly as sensitive as the state beside it, and it carries th
`TODO(security)` the rest of the store does. Phase 8 moves those bytes into one more table
and does not change what guards them.
## Phase 9 — the upgrade, made runnable
Phase 4 settled the blob and left the database alone, because there was no schema change
to worry about. Phase 8 added a table, and that turns "does an existing install still
open?" from a question about MLS into a question about Room. The two fail differently. A
blob the engine cannot read costs one room. A migration Room cannot find costs the app:
every device that has ever had it, on the first launch after the update, with an
`IllegalStateException` and no rooms at all.
That second failure is also the easiest one in this repository to ship by accident. An
entity added to the `@Database` list without an `AutoMigration` beside it compiles, and
it installs perfectly on a phone that has never had the app — a fresh install creates
every table at the current version and never migrates anything. Only a database that is
already there asks for the path that is missing. It was worth knowing how much of the
suite would notice, so the `AutoMigration(from = 36, to = 37)` line was commented out and
the database tests run: **32 tests, 4 failures, and all four of them the new ones.** Every
other migration test and every test over an in-memory database passed with the migration
gone.
So, `ShippedProfileUpgradeJvmTest`. A v36 database, built on disk from the exported v36
schema — its tables, its indices, its `room_master_table` identity hash and its
`user_version`, which together are what make Room read the file as a v36 install rather
than as a corrupt one — with a profile in it, two rooms, and the Phase 4 blob in one of
them. Then the app's own `getRoomDatabase` over that file, and four claims:
| | |
|---|---|
| it opens at v37, with the table this branch adds | `user_version` 37, the v37 identity hash stamped by Room, and every table's columns and indices equal to `37.json`'s |
| the legacy room survives and the engine opens it | the blob comes back out of the migrated file byte for byte, `MarmotEngine.groupFor` restores it, `0xF2EE` intact and a 32-byte kind:445 key, while the room beside it with no state comes back as no group |
| opening the profile rewrites nothing | the restore picks the room up and leaves its bytes exactly as they were |
| the added table takes a row keyed to a room that predates it | the one direction an added table's foreign key can be wrong in: it points at `ChatRoom`, which was already there with rows in it |
The third one is the one worth arguing for, because it asserts an absence. Restoring a
group re-derives its key schedule and could just as well save the result at the current
state version — and the first thing that persists each room will do exactly that, which
is what Phase 4's re-save test pins. Doing it to *every* room at once, on the first launch
after an upgrade, is a different thing: it is the one moment when every room's only copy
is being rewritten, and a crash in the middle of it has nothing underneath. The absence is
the claim, so the test first asserts the restore actually held the room — otherwise it
would be the absence of a write by an engine holding nothing, which is not the same
sentence.
**One gotcha, which cost the first run.** `Room.databaseBuilder(...).build()` does not
touch the file. Room opens lazily and the migration runs on the first query, so a test
that builds a database and closes it has migrated nothing; the helper has to ask it
something. The first version of this test did exactly that and failed on `user_version`
still reading 36.
**And the fixture moved.** The Phase 4 blob is now `OldEngineBlob` in `commonTest`, used
by both tests rather than copied into the second. The point of those bytes is that they
are *old* ones, and a blob living in two files can be regenerated in one of them — after
which the copy that was left alone is the only evidence, with nothing on either saying
which is which.
**Built.** 1171 tests across 157 classes, 0 failures; the four audits unchanged. The tool
in `docs/tools/old-state-blob/` is untouched: its job was always provenance for those
bytes, and this phase gives them a second reader rather than a new source.
**What is still manual.** A fixture is a profile with two rooms in it, one of them a group
at epoch 0 with a single member. A real profile has rooms that have been through several
epochs, several members and a retained-epoch window, and rows in forty-odd other tables
that this plants placeholders in. The schema path is now covered on every launch of
`./gradlew check`; the data is not, and opening one real profile is still the last check
before a release.
## Out of scope
`marmot-quic` and agent text streams. MIP-04 encrypted media and the Blossom image
+13 -7
View File
@@ -2,17 +2,23 @@
A throwaway project whose only dependency is the engine the app shipped before it moved to
marmot-kmp: `com.vitorpamplona.quartz:quartz:1.15.2`. It prints a `MlsGroupState`
TLS blob, at the `STATE_VERSION = 4` that version wrote, for
`MlsGroupStateCompatibilityTest` to decode with mls-kmp.
TLS blob, at the `STATE_VERSION = 4` that version wrote.
What it printed is pinned in `OldEngineBlob`, in `commonTest`, and two tests read it from
there: `MlsGroupStateCompatibilityTest` decodes it with mls-kmp, and
`ShippedProfileUpgradeJvmTest` puts it in a database at the schema version the app ships
and opens that database with the app's own builder (docs/marmot-kmp.md, Phases 4 and 9).
One copy, because the only thing that makes those bytes worth anything is that they are
old ones, and a blob living in two files can be regenerated in one of them.
```bash
../../../gradlew --project-dir . -q run
```
It is here for provenance. The fixture in that test has to be bytes the *old* engine
wrote, so regenerating it with the engine the app now ships would defeat the point of the
test -- and once this project is gone there is no way to tell the difference by reading
the hex. It is not part of the root build (its own `settings.gradle.kts` makes it a build
It is here for provenance. The fixture has to be bytes the *old* engine wrote, so
regenerating it with the engine the app now ships would defeat the point of both tests --
and once this project is gone there is no way to tell the difference by reading the hex. It is not part of the root build (its own `settings.gradle.kts` makes it a build
of its own), and nothing in `./gradlew check` runs it.
Not a general-purpose tool: it is the one blob Phase 4 of docs/marmot-kmp.md needed.
Not a general-purpose tool: it is the one blob Phase 4 of docs/marmot-kmp.md needed, and
Phase 9 found a second use for rather than a second source.
@@ -5,8 +5,10 @@ import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
/**
* Writes an MLS group state blob with the engine the app shipped before it moved to
* marmot-kmp: quartz 1.15.2, STATE_VERSION 4. The blob is the fixture
* `MlsGroupStateCompatibilityJvmTest` then decodes with mls-kmp. docs/marmot-kmp.md, Phase 4.
* marmot-kmp: quartz 1.15.2, STATE_VERSION 4. The blob is pinned as `OldEngineBlob` and read
* by `MlsGroupStateCompatibilityTest`, which decodes it with mls-kmp, and by
* `ShippedProfileUpgradeJvmTest`, which opens a v36 database holding it.
* docs/marmot-kmp.md, Phases 4 and 9.
*
* Deterministic where it can be: the identity and the group id are fixed, so re-running
* this prints a blob of the same shape. The keys inside are random by construction.