feat(marmot): publish before apply (v2 Phase 6)

A commit this device makes into an established current-profile room is no
longer applied and then broadcast. It is prepared on a clone by the manager,
recorded as a durable obligation before anything is broadcast, sent, and
installed only when a relay in its scope accepts it. docs/marmot-v2.md, Phase 6.

The library's gate explains why apply-and-roll-back is not the same thing:
between applying a local commit and undoing it on failure there is a window in
which this client's canonical state is an epoch no peer has, and a crash inside
it makes the fork permanent. Recording the obligation before the broadcast
closes the mirror-image window -- a commit peers accepted that this device has
no memory of preparing, and would mint a replacement for at the next start.

Two new tables (schema 22 -> 23), MarmotPublishObligation and MarmotOutboundGate,
back RoomPublishObligationStore; MarmotEngine holds a MarmotPublishGate over it
and restores it after the groups. MarmotCommitResult -- the row that already
held a commit's Welcome until the relay's OK -- carries the obligation id, and
DatabaseNostrRepository.broadcastProcessed resolves it on "published" through
MarmotEngine.confirmPublished, which installs the pending state, tells
convergence of the commit we authored (without which a peer's competing commit
would look like an orphan rather than a fork we are half of), and only then
lets the Welcome go out: the MIP-02 ordering enforced by sequence rather than by
hope. A second OK for the same event from another relay finds no obligation
and changes nothing.

The founding Add keeps its exception. A group that is only its creator has no
peer a failure to publish could fork, so it installs at once -- the library's
satisfyEmptyObligation draws the same line, "creation and its immediately
following founding Add, never a later commit". While an obligation is pending
the room cannot prepare another commit: a second invite is refused with
MarmotCommitPendingException, shown as itself on the confirmation screen, rather
than forked; the membership note's batching closed the race inside one invite,
and this closes it between invites. The broadcast queue's requeue re-sends the
same signed event, which is the byte-identical retry the rule demands, and a
"failed" from the pump -- a timeout or a relay's refusal, which the pump does
not tell apart -- leaves the obligation pending rather than discarding a state
some relay may have taken. Legacy rooms are unchanged.

Tests: PublishBeforeApplyJvmTest pins the founding Add installing at once, a
later commit prepared and queued but not applied, the second Welcome held back,
a concurrent invite refused, the OK installing the state and queueing the
Welcome, a second OK changing nothing, and an obligation restored by an engine
rebuilt over the same database and installed by a late OK. Full JVM suite:
1,177 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5 committed 2026-09-13 23:27:40 +02:00
1 parent 8e1037dff1
commit f617560cf9
12 files changed
+6202 -12

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -42,6 +42,7 @@ import to.curare.compose.database.dao.MarmotGroupEventDao
import to.curare.compose.database.dao.MarmotInnerEventDao
import to.curare.compose.database.dao.MarmotKeyPackageBundleDao
import to.curare.compose.database.dao.MarmotRoutingDao
import to.curare.compose.database.dao.MarmotPublishObligationDao
import to.curare.compose.database.dao.MarmotKeyPackageDao
import to.curare.compose.database.dao.MarmotRetainedEpochSecretDao
import to.curare.compose.database.dao.MentionDao
@@ -95,6 +96,8 @@ import to.curare.compose.database.model.MarmotInnerEvent
import to.curare.compose.database.model.MarmotKeyPackage
import to.curare.compose.database.model.MarmotKeyPackageBundle
import to.curare.compose.database.model.MarmotRouting
import to.curare.compose.database.model.MarmotPublishObligation
import to.curare.compose.database.model.MarmotOutboundGate
import to.curare.compose.managers.MarmotEngine
import to.curare.compose.database.model.MarmotRetainedEpochSecret
import to.curare.compose.database.model.Mention
@@ -162,6 +165,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
MarmotKeyPackage::class,
MarmotKeyPackageBundle::class,
MarmotRouting::class,
MarmotPublishObligation::class,
MarmotOutboundGate::class,
MarmotRetainedEpochSecret::class,
Mention::class,
NegentropySynchronizeRequest::class,
@@ -181,7 +186,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 22,
version = 23,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -341,6 +346,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// through this table. No rows are backfilled: a room with none is addressed
// by its own id, which is what every room before the table was.
AutoMigration(from = 21, to = 22),
// v23 adds MarmotPublishObligation and MarmotOutboundGate: the commits this
// device prepared and has not yet heard a relay accept, and the gates a room
// is under (docs/marmot-v2.md, Phase 6). Both have to outlive the process --
// an obligation forgotten at a crash is a replacement commit at the next
// start, which forks the group against whoever took the first one.
AutoMigration(from = 22, to = 23),
]
)
@ColumnTypeConverters(CurareConverters::class)
@@ -418,6 +429,7 @@ abstract class CurareDatabase: RoomDatabase() {
abstract fun marmotKeyPackageBundleDao(): MarmotKeyPackageBundleDao
abstract fun marmotRoutingDao(): MarmotRoutingDao
abstract fun marmotPublishObligationDao(): MarmotPublishObligationDao
abstract fun marmotKeyPackageDao(): MarmotKeyPackageDao
@@ -21,6 +21,7 @@ import to.curare.compose.nostr.MarmotProfile
import to.curare.compose.database.model.MarmotRetainedEpochSecret
import to.curare.compose.database.model.NostrEvent
import to.curare.compose.database.model.Participant
import to.curare.compose.exceptions.MarmotCommitPendingException
import to.curare.compose.exceptions.MarmotKeyPackageProfileException
import to.curare.compose.exceptions.MarmotMissingChatGroupException
import to.curare.compose.database.model.intermdiate.LocalChatRoom
@@ -587,14 +588,32 @@ abstract class MarmotOutboundDao(
content = "Invited ${memberName(peerPublicKey)} to the group",
)
var obligationId: HexKey? = null
val commitResult = if (mlsGroup.currentGroupState().isCurrentProfile) {
// Staged on a clone and installed at once by the manager, which retains
// the epoch it is leaving and persists the state itself; the caller
// must not write it back. Installing here rather than on a relay's OK
// is what docs/marmot-v2.md Phase 6 changes.
val manager = database.marmotEngine.groupManager
val staged = manager.stageAddMember(routingId, peerKeyPackage.tlsEncodedMarmotKeyPackage)
manager.installState(routingId, staged.pendingState)
// Staged on a clone by the manager, which persists nothing yet. The
// founding Add -- a group that is only its creator -- is installed at
// once, which is the one exception publish-before-apply allows: there
// is no peer a failure to publish could fork. Every later commit is
// recorded as an obligation, durable before anything is broadcast, and
// installed only when a relay accepts it: MarmotEngine.confirmPublished,
// from the relay's OK. See docs/marmot-v2.md, Phase 6.
val engine = database.marmotEngine
if (!isOneMemberInitialGroupCreation && !engine.gate.canPrepareLocalCommit(routingId)) {
throw MarmotCommitPendingException(
"An earlier change to this room is still waiting for a relay to accept it; try again in a moment"
)
}
val staged = engine.groupManager.stageAddMember(routingId, peerKeyPackage.tlsEncodedMarmotKeyPackage)
if (isOneMemberInitialGroupCreation) {
engine.groupManager.installState(routingId, staged.pendingState)
} else {
obligationId = engine.gate.prepare(
groupId = routingId,
staged = staged,
outboundBytes = staged.result.framedCommitBytes,
recipientScope = relays,
).obligationId
}
staged.result
} else {
val retainedBefore = mlsGroup.retainedSecrets()
@@ -689,7 +708,8 @@ abstract class MarmotOutboundDao(
userPublicKey = userPublicKey,
peerKeyPackageEventId = peerKeyPackage.id,
isOneMemberInitialGroupCreation = isOneMemberInitialGroupCreation,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt)
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
obligationId = obligationId,
)
)
@@ -0,0 +1,29 @@
package to.curare.compose.database.dao
import androidx.room3.Dao
import androidx.room3.Query
import androidx.room3.Upsert
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import to.curare.compose.database.model.MarmotOutboundGate
import to.curare.compose.database.model.MarmotPublishObligation
@Dao
interface MarmotPublishObligationDao {
@Upsert
suspend fun upsert(obligation: MarmotPublishObligation)
@Query("DELETE FROM MarmotPublishObligation WHERE obligationId = :obligationId")
suspend fun delete(obligationId: HexKey)
@Query("SELECT * FROM MarmotPublishObligation")
suspend fun getAll(): List<MarmotPublishObligation>
@Upsert
suspend fun upsertGate(gate: MarmotOutboundGate)
@Query("DELETE FROM MarmotOutboundGate WHERE groupId = :groupId")
suspend fun deleteGate(groupId: HexKey)
@Query("SELECT * FROM MarmotOutboundGate")
suspend fun getAllGates(): List<MarmotOutboundGate>
}
@@ -54,6 +54,15 @@ data class MarmotCommitResult( // TODO: Rename this to GiftWrapPayload...
*/
val preCommitExporterSecret: ByteArray = ByteArray(0),
/**
* The publish obligation this commit is the outbound half of, or null for a
* commit applied before it was published -- every legacy room's, and every
* current-profile room's before docs/marmot-v2.md Phase 6. A relay's OK on the
* commit event resolves it, which installs the pending state, before the Welcome
* this row also holds goes out.
*/
val obligationId: HexKey? = null,
/**
* Current time
*/
@@ -94,6 +103,7 @@ data class MarmotCommitResult( // TODO: Rename this to GiftWrapPayload...
peerKeyPackageEventId: HexKey,
isOneMemberInitialGroupCreation: Boolean,
createdAt: Instant,
obligationId: HexKey? = null,
): MarmotCommitResult = MarmotCommitResult(
id = commitEventId,
userPublicKey = userPublicKey,
@@ -105,6 +115,7 @@ data class MarmotCommitResult( // TODO: Rename this to GiftWrapPayload...
groupInfoBytes = commitResult.groupInfoBytes,
framedCommitBytes = commitResult.framedCommitBytes,
preCommitExporterSecret = commitResult.preCommitExporterSecret,
obligationId = obligationId,
createdAt = createdAt,
)
}
@@ -117,6 +128,7 @@ data class MarmotCommitResult( // TODO: Rename this to GiftWrapPayload...
if (isOneMemberInitialGroupCreation != other.isOneMemberInitialGroupCreation) return false
if (id != other.id) return false
if (obligationId != other.obligationId) return false
if (userPublicKey != other.userPublicKey) return false
if (chatRoomId != other.chatRoomId) return false
if (!commitBytes.contentEquals(other.commitBytes)) return false
@@ -137,6 +149,7 @@ data class MarmotCommitResult( // TODO: Rename this to GiftWrapPayload...
override fun hashCode(): Int {
var result = isOneMemberInitialGroupCreation.hashCode()
result = 31 * result + id.hashCode()
result = 31 * result + (obligationId?.hashCode() ?: 0)
result = 31 * result + userPublicKey.hashCode()
result = 31 * result + chatRoomId.hashCode()
result = 31 * result + commitBytes.contentHashCode()
@@ -0,0 +1,46 @@
package to.curare.compose.database.model
import androidx.room3.Entity
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
/**
* A commit this device prepared and has not yet heard a relay accept.
*
* Publish-before-apply (`protocol-core/publish-lifecycle.md`): a locally generated
* group-state change must not become canonical until a relay in its scope has
* acknowledged it, and the record has to be durable *before* anything is broadcast
* -- publishing first and recording after leaves a crash window in which peers hold
* a commit this device has no memory of preparing, and the next start would mint a
* replacement, forking the group against everyone who took the first one.
*
* The bytes are the library's own encoding of `MarmotPublishObligation` -- the
* outbound MLS bytes, their recipient scope, the state they were made from and the
* state they would make canonical -- opaque here, because the gate decodes them.
* See docs/marmot-v2.md, Phase 6.
*/
@Entity
data class MarmotPublishObligation(
/** `SHA-256` of the outbound bytes; the same id a retry carries. */
@PrimaryKey
val obligationId: HexKey,
val bytes: ByteArray,
) {
override fun equals(other: Any?): Boolean =
this === other || (other is MarmotPublishObligation && obligationId == other.obligationId && bytes.contentEquals(other.bytes))
override fun hashCode(): Int = 31 * obligationId.hashCode() + bytes.contentHashCode()
}
/**
* An outbound gate a group is under -- `LEAVING`, `DISBANDING`, `REMOVED` -- which
* blocks new local commits and has to survive a restart: a disband that is only in
* memory is lost by the crash between raising it and publishing the commit.
*/
@Entity
data class MarmotOutboundGate(
/** The routing address the library gates by. */
@PrimaryKey
val groupId: HexKey,
val gate: String,
)
@@ -506,6 +506,15 @@ class DatabaseNostrRepository(
nostrEventId = broadcastNostrEventRequest.nostrEventId
)?.let { marmotCommitResult ->
logger.d("marmotCommitResult: $marmotCommitResult")
// Publish before apply: a relay accepted the commit, so the state it
// makes canonical is installed now -- and only now, and before the
// Welcome below, which is the MIP-02 ordering enforced by sequence
// rather than by hope. See docs/marmot-v2.md, Phase 6.
marmotCommitResult.obligationId?.let { obligationId ->
database.marmotEngine.confirmPublished(obligationId)
}
if (marmotCommitResult.isOneMemberInitialGroupCreation.not()) {
logger.d("Deliver Welcome")
database.chatRoomDao().findChatRoomById(marmotCommitResult.chatRoomId)?.let { localChatRoom ->
@@ -0,0 +1,10 @@
package to.curare.compose.exceptions
/**
* The room has a commit of its own still waiting for a relay to accept it, so no
* new one may be prepared: a second commit at the same epoch would be a fork this
* device caused itself. The state it describes -- an invite, say -- is not lost;
* the earlier one lands, and this is asked for again. See docs/marmot-v2.md,
* Phase 6.
*/
class MarmotCommitPendingException(message: String? = null, cause: Throwable? = null) : Exception(message, cause)
@@ -8,6 +8,8 @@ import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageRotationManage
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupManager
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupState
import com.vitorpamplona.quartz.marmot.protocolCore.MarmotPublishGate
import com.vitorpamplona.quartz.marmot.protocolCore.PublishOutcome
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -58,6 +60,13 @@ class MarmotEngine(
val inbound = MarmotInboundProcessor(groupManager, KeyPackageRotationManager())
val outbound = MarmotOutboundProcessor(groupManager)
/**
* Publish-before-apply for the commits this device makes: a commit is prepared
* on a clone, recorded durably, broadcast, and installed only when a relay in its
* scope has accepted it. See [RoomPublishObligationStore] and Phase 6.
*/
val gate = MarmotPublishGate(groupManager, RoomPublishObligationStore(database))
private val restoreMutex = Mutex()
private var restored = false
@@ -72,6 +81,9 @@ class MarmotEngine(
if (restored) return
groupManager.restoreAll()
groupManager.activeGroupIds().forEach { inbound.trackGroup(it) }
// After the groups: an obligation restored names states of a group the
// manager has to hold already.
gate.restore()
restored = true
logger.d("Restored ${groupManager.activeGroupIds().size} group(s)")
}
@@ -94,6 +106,26 @@ class MarmotEngine(
return group
}
/**
* A relay accepted the commit behind [obligationId]: the pending state becomes
* canonical, and convergence learns of the commit we authored -- without which a
* peer's competing commit would look like an orphan rather than a fork we are
* half of. Nothing to do for an obligation the gate no longer holds, which is a
* second OK for the same event from another relay.
*/
suspend fun confirmPublished(obligationId: HexKey) {
ensureRestored()
val obligation = gate.allPending().firstOrNull { it.obligationId == obligationId } ?: return
gate.resolve(obligationId, PublishOutcome.CONFIRMED)
inbound.recordLocalCommit(
groupId = obligation.groupId,
framedCommitBytes = obligation.outboundBytes,
sourceEpoch = obligation.priorState.groupContext.epoch,
preState = obligation.priorState,
)
logger.i("Commit ${obligationId.take(8)}… confirmed; ${obligation.groupId.take(8)}… is at epoch ${obligation.pendingState.groupContext.epoch}")
}
/**
* Tick convergence, and keep ticking while any pass is open.
*
@@ -0,0 +1,37 @@
package to.curare.compose.managers
import com.vitorpamplona.quartz.marmot.protocolCore.MarmotPublishObligationStore
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.model.MarmotOutboundGate
import to.curare.compose.database.model.MarmotPublishObligation
/**
* The publish gate's durable half, over the app's tables. See
* [to.curare.compose.database.model.MarmotPublishObligation].
*/
class RoomPublishObligationStore(
private val database: CurareDatabase,
) : MarmotPublishObligationStore {
override suspend fun save(obligationId: HexKey, bytes: ByteArray) {
database.marmotPublishObligationDao().upsert(MarmotPublishObligation(obligationId, bytes))
}
override suspend fun delete(obligationId: HexKey) {
database.marmotPublishObligationDao().delete(obligationId)
}
override suspend fun loadAll(): List<ByteArray> =
database.marmotPublishObligationDao().getAll().map { it.bytes }
override suspend fun saveGate(groupId: HexKey, gate: String) {
database.marmotPublishObligationDao().upsertGate(MarmotOutboundGate(groupId, gate))
}
override suspend fun deleteGate(groupId: HexKey) {
database.marmotPublishObligationDao().deleteGate(groupId)
}
override suspend fun loadGates(): Map<HexKey, String> =
database.marmotPublishObligationDao().getAllGates().associate { it.groupId to it.gate }
}
@@ -10,6 +10,7 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import to.curare.compose.database.model.MarmotKeyPackage
import to.curare.compose.exceptions.MarmotCommitPendingException
import to.curare.compose.exceptions.MarmotKeyPackageProfileException
import to.curare.compose.nostr.MarmotProfile
import to.curare.compose.database.model.NegentropySynchronizeRequest
@@ -147,10 +148,13 @@ class AddMemberToChatRoomConfirmationViewModel(
logger.e("Failed to invite $peerPublicKey to ${localChatRoom.chatRoom.id}", e)
isActionPending.value = false
// A key package on the wrong profile is the one failure the member can
// fix, so it is shown as itself rather than as "try again".
// fix, and a commit still waiting for a relay is the one that fixes
// itself, so both are shown as themselves rather than as "try again".
addMemberToChatRoomConfirmationUIState = AddMemberToChatRoomConfirmationUIState.Error(
(e as? MarmotKeyPackageProfileException)?.message
?: "Couldn't send the invite. Please try again."
when (e) {
is MarmotKeyPackageProfileException, is MarmotCommitPendingException -> e.message
else -> null
} ?: "Couldn't send the invite. Please try again."
)
return@launch
}
@@ -0,0 +1,153 @@
package to.curare.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.marmot.appComponents.CurrentProfileGroupFactory
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.builder.getRoomDatabase
import to.curare.compose.database.model.MarmotKeyPackage
import to.curare.compose.database.model.NostrEvent
import to.curare.compose.database.model.Profile
import to.curare.compose.database.repository.DatabaseChatRepository
import to.curare.compose.database.repository.DatabaseNostrRepository
import to.curare.compose.exceptions.MarmotCommitPendingException
import to.curare.compose.nostr.MarmotProfile
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Publish before apply, for a current-profile room. docs/marmot-v2.md, Phase 6.
*
* The founding Add -- a group that is only its creator -- is the one exception and
* installs at once. Every commit after it is prepared on a clone, recorded durably,
* broadcast, and installed only when a relay accepts it; meanwhile a second commit
* is refused rather than forked, and a restart resumes the obligation from disk.
*/
class PublishBeforeApplyJvmTest {
private val db: CurareDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<CurareDatabase>())
private val scope = CoroutineScope(Dispatchers.Default)
private val chatRepository = DatabaseChatRepository(db, scope)
private val nostrRepository = DatabaseNostrRepository(db, scope)
@AfterTest
fun closeDb() = db.close()
private val keyPair = KeyPair()
private val user = keyPair.pubKey.toHexKey()
private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey())
private suspend fun seedProfile(publicKey: String) {
val eventId = publicKey.take(32).padEnd(64, 'f')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(8), nostrEventId = eventId))
}
/** A peer's current-profile package, as the ingest would have stored it. */
private suspend fun peerPackage(peer: KeyPair): MarmotKeyPackage {
seedProfile(peer.pubKey.toHexKey())
val keyPackage = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(peer)).keyPackage
return MarmotKeyPackage(
id = peer.pubKey.toHexKey(), publicKey = peer.pubKey.toHexKey(),
tlsEncodedMarmotKeyPackage = keyPackage.toTlsBytes(), profile = MarmotProfile.CURRENT.wireName,
)
}
/** A current-profile room whose founding Add has landed: two members at epoch 1. */
private suspend fun establishedRoom(): String {
seedProfile(user)
val outcome = MarmotGroupCreation.create(
database = db, chatRepository = chatRepository, groupId = roomId, name = "#room",
purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair,
profile = MarmotProfile.CURRENT,
)
assertIs<MarmotGroupCreation.Outcome.Created>(outcome)
val first = KeyPair()
chatRepository.inviteMember(db.chatRoomDao().findChatRoomById(roomId)!!, first.pubKey.toHexKey(), peerPackage(first))
assertEquals(1L, epochOnDisk(), "the founding Add installs at once")
return db.marmotRoutingDao().activeRoutingIdFor(roomId)
}
private suspend fun epochOnDisk(): Long = db.chatRoomDao().findChatRoomById(roomId)!!.chatRoom.toMlsGroup()!!.epoch
private suspend fun commitEventFor(peer: KeyPair) =
db.marmotCommitResultDao().let { dao ->
db.nostrEventDao().getMLSGroupEvents(since = kotlin.time.Instant.fromEpochSeconds(0), limit = 10)
.filter { it.kind == GroupEvent.KIND }
.mapNotNull { event -> dao.getMarmotCommitRequestById(event.id)?.let { event to it } }
.single { (_, result) -> result.peerKeyPackageEventId == peer.pubKey.toHexKey() }
}
@Test
fun `a commit into an established room waits for a relay before it is applied`() = runBlocking {
val routingId = establishedRoom()
val second = KeyPair()
chatRepository.inviteMember(db.chatRoomDao().findChatRoomById(roomId)!!, second.pubKey.toHexKey(), peerPackage(second))
// Prepared, recorded, broadcast -- and not applied.
assertEquals(1L, epochOnDisk(), "the commit was applied before any relay accepted it")
val (commitEvent, result) = commitEventFor(second)
val obligationId = assertNotNull(result.obligationId, "the commit carries no obligation")
assertEquals(1, db.marmotPublishObligationDao().getAll().size)
assertTrue(db.marmotEngine.gate.pendingFor(routingId).any { it.obligationId == obligationId })
assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(commitEvent.id), "nothing queued to broadcast")
// One Welcome so far: the founding member's. The second's waits for the OK.
assertEquals(1, db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.chatRoomId == roomId && it.kind == 444 }, "the Welcome went out before the commit was accepted")
// A second change while the first is unacknowledged is refused, not forked.
val third = KeyPair()
val thirdPackage = peerPackage(third)
assertFailsWith<MarmotCommitPendingException> {
chatRepository.inviteMember(db.chatRoomDao().findChatRoomById(roomId)!!, third.pubKey.toHexKey(), thirdPackage)
}
// The OK: installed, forgotten, and the Welcome queued after it.
val request = db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(commitEvent.id)!!
nostrRepository.broadcastProcessed(request, "published")
assertEquals(2L, epochOnDisk(), "the OK did not install the pending state")
assertTrue(db.marmotEngine.groupManager.getGroup(routingId)!!.currentMemberIdentities().contains(second.pubKey.toHexKey()))
assertEquals(0, db.marmotPublishObligationDao().getAll().size)
assertTrue(db.marmotEngine.gate.canPrepareLocalCommit(routingId))
assertEquals(2, db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.chatRoomId == roomId && it.kind == 444 }, "no Welcome was queued for the second member")
// A second OK from another relay changes nothing.
nostrRepository.broadcastProcessed(request, "published")
assertEquals(2L, epochOnDisk())
}
@Test
fun `an obligation survives a restart and a late OK installs it`() = runBlocking {
val routingId = establishedRoom()
val second = KeyPair()
chatRepository.inviteMember(db.chatRoomDao().findChatRoomById(roomId)!!, second.pubKey.toHexKey(), peerPackage(second))
val (_, result) = commitEventFor(second)
val obligationId = assertNotNull(result.obligationId)
// A new engine over the same database: what a relaunch builds.
val rebuilt = MarmotEngine(db)
rebuilt.ensureRestored()
assertEquals(1L, epochOnDisk())
assertTrue(rebuilt.gate.pendingFor(routingId).any { it.obligationId == obligationId }, "the obligation was not restored")
assertTrue(!rebuilt.gate.canPrepareLocalCommit(routingId))
rebuilt.confirmPublished(obligationId)
assertEquals(2L, epochOnDisk())
assertNull(db.marmotPublishObligationDao().getAll().firstOrNull())
assertTrue(rebuilt.gate.canPrepareLocalCommit(routingId))
}
}