Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -318,14 +318,19 @@ interface DirtyOperationDao {
"AND state = 'membership_ready' ORDER BY id LIMIT :limit")
suspend fun readyMembershipCommands(authority: String, limit: Int): List<DirtyOperationEntity>

/** Membership rows never enter the legacy retry/drain states. */
@Query("DELETE FROM dirty_operations WHERE coalesceKey = :key AND state = 'membership_ready'")
suspend fun deleteReadyMembership(key: String)
/**
* Membership rows never enter the legacy retry/drain states. A newer choice replaces every
* older command for the item that isn't mid-send, so a later retry can't resend an old one
* after the newer command is acknowledged and deleted.
*/
@Query("DELETE FROM dirty_operations WHERE coalesceKey = :key " +
"AND state IN ('membership_ready', 'membership_reconcile', 'membership_paused')")
suspend fun deleteReplacedMembership(key: String)

@Transaction
suspend fun enqueueMembership(op: DirtyOperationEntity): Long {
require(op.state == "membership_ready" && !op.membershipAuthority.isNullOrBlank())
deleteReadyMembership(op.coalesceKey)
deleteReplacedMembership(op.coalesceKey)
return insert(op)
}

Expand All @@ -335,6 +340,22 @@ interface DirtyOperationDao {
"WHERE older.coalesceKey = dirty_operations.coalesceKey AND older.state = 'membership_sending')")
suspend fun claimMembership(id: Long, authority: String, claim: String, owner: String): Int

/**
* Resends a paused command only while it is the item's latest one, no sibling is sending, and
* the item's projection doesn't name a newer command (one that was acknowledged and deleted).
*/
@Query("UPDATE dirty_operations SET state = 'membership_sending', membershipClaim = :claim, " +
"membershipOwner = :owner WHERE id = :id AND membershipAuthority = :authority " +
"AND membershipClaim = :previousClaim AND state = 'membership_paused' AND NOT EXISTS (SELECT 1 " +
"FROM dirty_operations other WHERE other.coalesceKey = dirty_operations.coalesceKey " +
"AND other.id != dirty_operations.id AND other.state != 'legacy_membership_quarantined' " +
"AND (other.id > dirty_operations.id OR other.state = 'membership_sending')) " +
"AND NOT EXISTS (SELECT 1 FROM membership_projection projection WHERE projection.authority = :authority " +
"AND projection.itemId = dirty_operations.targetContentId " +
"AND projection.kind = substr(dirty_operations.opKind, length('MEMBERSHIP_') + 1) " +
"AND projection.commandId != dirty_operations.id)")
suspend fun reclaimMembership(id: Long, authority: String, previousClaim: String, claim: String, owner: String): Int
Comment thread
Quick104 marked this conversation as resolved.
Resolved

@Query("UPDATE dirty_operations SET state = :state WHERE id = :id AND membershipClaim = :claim " +
"AND membershipAuthority = :authority AND state = :expectedState")
suspend fun transitionMembership(id: Long, claim: String, authority: String, expectedState: String, state: String): Int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import org.siloserver.silo.network.TokenManager
import org.siloserver.silo.network.apiv2.MembershipV2Api

/**
* Storage foundation only. Both inline and worker sends must use [send] after activation.
* Storage foundation only. Both inline and worker sends must use [send] or [retry] after activation.
* [authority] is a persisted login identity, NOT a server/profile pair or process counter.
* The caller must verify its association with [scope] before constructing an Authority.
* No credentials are persisted in Room. A process owns one instance and calls [recover]
Expand Down Expand Up @@ -52,12 +52,16 @@ class MembershipOutbox(
))
}

suspend fun send(id: Long, authority: Authority): Result {
suspend fun send(id: Long, authority: Authority): Result =
sendClaimed(id, authority) { claim -> dao.claimMembership(id, authority.key, claim, processOwner) }

private suspend fun sendClaimed(id: Long, authority: Authority, claimRow: suspend (String) -> Int): Result {
if (authority.scope != tokens.snapshotCurrentScope()) return Result(Resolution.NOT_CLAIMED)
val claim = UUID.randomUUID().toString()
var resolved = false
var refused = false
try {
if (dao.claimMembership(id, authority.key, claim, processOwner) != 1) return Result(Resolution.NOT_CLAIMED)
if (claimRow(claim) != 1) return Result(Resolution.NOT_CLAIMED)
val command = requireNotNull(dao.getById(id))
require(command.serverId == authority.scope.serverId && command.profileId == authority.scope.profileId.orEmpty())
val present = command.payloadJson.toBooleanStrict()
Expand All @@ -73,7 +77,7 @@ class MembershipOutbox(
if (resolved) return Result(Resolution.ACKNOWLEDGED,
dao.getLatestByCoalesceKey(command.coalesceKey) == null && authority.scope == tokens.snapshotCurrentScope())
}
return Result(Resolution.NEEDS_RECONCILIATION)
refused = response is ApiResult.Error && refuses(response.code)
} finally {
// Claim commit can precede cancellation of its suspended return. Always attempt
// exact-token cleanup, even when admission never returned to this coroutine.
Expand All @@ -82,9 +86,44 @@ class MembershipOutbox(
dao.transitionMembership(id, claim, authority.key, SENDING, RECONCILE)
}
}
// Resending can't fix a refused write (an item that is gone or hidden). Read once instead:
// a removal of an item that is gone already matches; otherwise the command pauses.
return if (refused) reconcile(id, authority) else Result(Resolution.NEEDS_RECONCILIATION)
Comment on lines +89 to +91

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug high

Failed reconciliation causes definitively refused writes to be resent

If the follow-up read fails after a definitive refusal, MembershipActions.recover automatically resends the write. Persist the refusal independently of the read result and exclude it from automatic retries until the viewer explicitly retries.

Prompt for LLM
File android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/MembershipOutbox.kt, lines 89-91:

Failed reconciliation causes definitively refused writes to be resent

If the read after a 400, 404, 410, or 422 fails, `reconcile` returns `NEEDS_RECONCILIATION`, so `MembershipActions.recover` automatically resends the write despite the definitive refusal. Persist the refusal independently of the read result and keep it out of automatic mutation retries until the viewer explicitly retries.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

}

/**
* Recovers an unconfirmed command. A read that already shows the desired state resolves it;
* otherwise the command is resent, but only while it is still the item's latest choice.
* PUT and DELETE are idempotent, so resending a write that did land is harmless.
*/
suspend fun retry(id: Long, authority: Authority): Result {
Comment thread
Quick104 marked this conversation as resolved.
Resolved
// Cancelled between record and send: nothing was sent yet, so send it through the usual claim.
if (dao.getById(id)?.state == READY) return send(id, authority)
val observed = reconcile(id, authority)
if (observed.resolution != Resolution.PAUSED) return observed
val command = dao.getById(id) ?: return Result(Resolution.NOT_CLAIMED)
val previous = command.membershipClaim ?: return Result(Resolution.NOT_CLAIMED)
if (dao.getLatestByCoalesceKey(command.coalesceKey)?.id != id) {
// A newer choice for the same item replaces this one.
dao.resolveMembership(id, previous, authority.key, PAUSED)
return Result(Resolution.NOT_CLAIMED)
}
return sendClaimed(id, authority) { claim -> dao.reclaimMembership(id, authority.key, previous, claim, processOwner) }
Comment on lines +106 to +111

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug critical

Stale-command replay in MembershipOutbox.kt occurs because latest-choice admission checks only remaining dirty rows: an older retry whose GET finishes after a newer command is acknowledged and deleted can reclaim itself and resend the opposite value, silently reversing the confirmed Favorites or Watchlist change. Validate the durable projection's commandId in the reclaim transaction, or atomically retire superseded uncertain rows when recording the newer choice.

Prompt for LLM

File android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/MembershipOutbox.kt:

Line 99 to 104:

Stale-command replay in MembershipOutbox.kt occurs because latest-choice admission checks only remaining dirty rows: an older retry whose GET finishes after a newer command is acknowledged and deleted can reclaim itself and resend the opposite value, silently reversing the confirmed Favorites or Watchlist change. Validate the durable projection's commandId in the reclaim transaction, or atomically retire superseded uncertain rows when recording the newer choice.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed. I reproduced it with a unit test on this head. Command A (favorite) is unconfirmed, and its retry is waiting on the GET. Command B (unfavorite) is enqueued, sent, and acknowledged, and its row is deleted. A's GET then reports a mismatch, A becomes the latest remaining row, reclaimMembership finds no newer row, and A sends its PUT. The server ends up favorited, while the viewer's last choice was unfavorite.

Repair: when a newer command is enqueued, enqueueMembership now deletes the item's older ready, reconcile and paused commands; before, it deleted only ready ones. A command that is mid-send is left alone, and it already blocks the newer command's claim until it finishes. An older retry that wakes up later finds its row gone and stops without sending. I took your second option rather than a projection check. It keeps the claim rules inside dirty_operations, and it also lets a newer acknowledgement publish when an older unconfirmed row would otherwise have lingered and blocked it.

I'm fixing this in a commit on this branch, so there's no need to change it yourself.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for reproducing it. Retiring the older ready, reconcile, and paused commands is a sound fix for this race, provided that cleanup and insertion of the newer command happen in the same transaction and reclaim still requires the old row to exist in its expected state.

That removes the stale command before the newer acknowledgement can erase the evidence of supersession. Keeping an in-flight send intact preserves the existing per-item serialization.

Keep your reproducer as a regression test: acknowledge and delete B before releasing A’s GET, then assert that A sends no late PUT and the confirmed state remains unfavorited.

I’ll leave the branch changes to you.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cde1ec6. enqueueMembership now deletes the item's older ready, reconcile and paused commands, and docs/membership-api-v2.md describes the rule. New test: MembershipOutboxTest.retryNeverOverwritesANewerChoiceThatLandedDuringItsRead. It failed on 7e4dfda, where the stale PUT was sent, and passes now with no PUT after the newer DELETE. retryDropsSupersededCommandWithoutSending now expects no read, because the superseded row is already gone when the retry starts. The shared, android-shared, phone and TV unit tests pass (5,880 tests, 0 failures).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks—based on the fix and regression results you reported, this addresses the original stale-command replay finding.

Retiring older ready, reconcile, and paused rows during enqueue prevents A from becoming eligible again after B is acknowledged and deleted. The new regression test covers the exact failing interleaving, and its fail-before/pass-after result demonstrates that the late PUT is prevented. Expecting no read in retryDropsSupersededCommandWithoutSending is also consistent with retiring the row earlier.

I have no further changes to request for this finding.

Comment thread
Quick104 marked this conversation as resolved.
Resolved
}

/** Explicit read-only recovery; a mismatch pauses for a new user command, never resends. */
/**
* The one automatic retry a command restored from an earlier run gets. Only a recent unconfirmed
* command is resent; a paused one (the viewer was told it wasn't saved, or the server refused it)
* or an older one is only read, so a stale choice never overwrites a newer change made elsewhere.
* [nowMs] is wall-clock time, compared with the command's [DirtyOperationEntity.createdAtMs].
*/
suspend fun restore(id: Long, authority: Authority, nowMs: Long = System.currentTimeMillis()): Result {
val command = dao.getById(id) ?: return Result(Resolution.NOT_CLAIMED)
val recent = nowMs - command.createdAtMs in 0..RESTORE_RESEND_WINDOW_MS
return if (command.state == RECONCILE && recent) retry(id, authority) else reconcile(id, authority)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Kody Rules high

Restored retries can overwrite a newer confirmed membership choice

An automatic retry can replay an older choice after a newer one has been acknowledged and removed, because retry checks only remaining dirty rows. Validate durable per-item ordering in the reclaim transaction, or atomically retire superseded uncertain commands when recording a newer choice.

Kody rule violation: Order queued mutations per operation and acknowledge the exact instance

Prompt for LLM
File android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/MembershipOutbox.kt, line 123:

Restored retries can overwrite a newer confirmed membership choice

This automatic retry can replay an older choice after a newer choice for the same item has already been acknowledged and removed. `retry` checks only the remaining dirty rows after its reconciliation read, so it can no longer see that newer completed operation. Validate the command against durable per-item ordering in the reclaim transaction, or atomically retire superseded uncertain commands when a newer choice is recorded.

Kody rule violation: [Order queued mutations per operation and acknowledge the exact instance](https://kodus.siloserver.org/settings/code-review/1247142403/kody-rules/71a0233b-1a93-47c0-a7b5-c9eb1e184cc5?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

}

/** Read-only check; a mismatch pauses the command until [retry] or a new user command. */
suspend fun reconcile(id: Long, authority: Authority): Result {
val command = dao.getById(id) ?: return Result(Resolution.NOT_CLAIMED)
if (command.membershipAuthority != authority.key || command.serverId != authority.scope.serverId ||
Expand Down Expand Up @@ -112,5 +151,14 @@ class MembershipOutbox(
const val SENDING = "membership_sending"
const val RECONCILE = "membership_reconcile"
const val PAUSED = "membership_paused"

/** How long after a choice a restored command may still be resent without the viewer asking. */
const val RESTORE_RESEND_WINDOW_MS = 10 * 60_000L

/**
* Responses a resend can't change. 401 is refreshed by the API; 403 can clear once the
* profile is verified again; 408 and 429 are transient.
*/
private fun refuses(code: Int) = code in setOf(400, 404, 410, 422)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@ class MembershipRuntime(
return outbox.reconcile(id, authority.commandAuthority())
}

suspend fun retry(id: Long, authority: DurableLoginAuthority): MembershipOutbox.Result {
awaitRecovery()
if (authority != authorities.snapshotDurableLoginAuthority()) return MembershipOutbox.Result(MembershipOutbox.Resolution.NOT_CLAIMED)
return outbox.retry(id, authority.commandAuthority())
}

suspend fun restore(id: Long, authority: DurableLoginAuthority): MembershipOutbox.Result {
awaitRecovery()
if (authority != authorities.snapshotDurableLoginAuthority()) return MembershipOutbox.Result(MembershipOutbox.Resolution.NOT_CLAIMED)
return outbox.restore(id, authority.commandAuthority())
}

/** Bounded READY-only selection. Uncertain/paused rows never trigger mutation retries. */
suspend fun readyCommands(authority: DurableLoginAuthority, limit: Int): List<Long> {
require(limit in 1..100)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,20 @@ class RoomMembershipPort(
override suspend fun reconcile(command: MembershipPort.Command): MembershipPort.Completion =
completion(command, runtime.reconcile(command.id, command.authority))

override suspend fun retry(command: MembershipPort.Command): MembershipPort.Completion =
Comment thread
Quick104 marked this conversation as resolved.
Resolved
completion(command, runtime.retry(command.id, command.authority))

override suspend fun restore(command: MembershipPort.Command): MembershipPort.Completion =
completion(command, runtime.restore(command.id, command.authority))

private suspend fun completion(command: MembershipPort.Command, result: MembershipOutbox.Result): MembershipPort.Completion {
val current = projection(command.authority, command.itemId, command.kind)
val durable = current?.disposition?.takeIf {
current.commandId == command.id && it in listOf(MembershipPort.Disposition.ACKNOWLEDGED, MembershipPort.Disposition.RECONCILED)
}
// The row is gone because this exact command was already confirmed, e.g. its acknowledgement
// committed as the caller was cancelled. Report that rather than a lost claim.
if (result.resolution == MembershipOutbox.Resolution.NOT_CLAIMED && durable != null) return MembershipPort.Completion(durable, true)
return MembershipPort.Completion(MembershipPort.Disposition.valueOf(result.resolution.name),
result.resolution in listOf(MembershipOutbox.Resolution.ACKNOWLEDGED, MembershipOutbox.Resolution.RECONCILED) &&
current?.commandId == command.id && current.disposition in listOf(
Expand All @@ -112,6 +124,8 @@ class RoomMembershipPort(
val disposition = when (command?.state) {
MembershipOutbox.RECONCILE -> MembershipPort.Disposition.NEEDS_RECONCILIATION
MembershipOutbox.PAUSED -> MembershipPort.Disposition.PAUSED
// A resend in flight; its earlier paused disposition no longer applies.
MembershipOutbox.SENDING -> null
else -> projection.disposition?.let(MembershipPort.Disposition::valueOf)
}
if (authority != runtime.captureAuthority()) return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import org.siloserver.silo.repository.port.MembershipPort
data class MembershipNotice(
val title: String,
val message: String,
/** "Check Status" once a command was recorded, otherwise "Try Again". */
val actionLabel: String,
val onAction: () -> Unit,
val onDismiss: () -> Unit,
Expand Down Expand Up @@ -74,9 +73,8 @@ fun MembershipNoticeHost(
val (intent, action) = shown
show(unconfirmedNotice(action, onDismiss = { raised = raised - intent }) {
raised = raised - intent
scope.launch {
if (action.command != null) actions.checkStatus(intent) else actions.perform(intent)
}
// Retries a recorded command (read first, resend only on mismatch), or sends it.
scope.launch { actions.perform(intent) }
})
} else if (legacy) {
LegacyMembershipBanner(onDismiss = actions::dismissLegacyNotice, modifier = legacyModifier)
Expand All @@ -91,7 +89,6 @@ private fun unconfirmedNotice(
): MembershipNotice {
val favorite = action.intent.key.kind == MembershipPort.Kind.FAVORITE
val adding = action.intent.present
val recorded = action.command != null
if (action.completion?.disposition == MembershipPort.Disposition.PAUSED) {
return MembershipNotice(
title = stringResource(R.string.shell_membership_notSaved_title),
Expand All @@ -103,7 +100,7 @@ private fun unconfirmedNotice(
else -> R.string.shell_membership_notSaved_removeWatchlist
},
),
actionLabel = stringResource(R.string.shell_membership_checkStatus),
actionLabel = stringResource(R.string.shell_membership_tryAgain),
onAction = onAction,
onDismiss = onDismiss,
)
Expand All @@ -116,15 +113,14 @@ private fun unconfirmedNotice(
else -> R.string.shell_membership_notConfirmed_removeWatchlist
},
)
val next = stringResource(
if (recorded) R.string.shell_membership_notConfirmed_checkLater else R.string.shell_membership_notConfirmed_retryLater,
)
return MembershipNotice(
title = stringResource(R.string.shell_membership_notConfirmed_title),
message = stringResource(R.string.shell_membership_notConfirmed_message, unconfirmed, next),
actionLabel = stringResource(
if (recorded) R.string.shell_membership_checkStatus else R.string.shell_membership_tryAgain,
message = stringResource(
R.string.shell_membership_notConfirmed_message,
unconfirmed,
stringResource(R.string.shell_membership_notConfirmed_retryLater),
),
actionLabel = stringResource(R.string.shell_membership_tryAgain),
onAction = onAction,
onDismiss = onDismiss,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,18 @@ class DormantMembershipTest {
port.projection(authority, "item", MembershipPort.Kind.WATCHLIST)?.disposition)
assertEquals(listOf(HttpMethod.Delete, HttpMethod.Get), methods)
}
@Test fun restartProjectsAbandonedClaimAsReadRecoveryAndMismatchPauses() = runTest {
@Test fun restartProjectsAbandonedClaimAsReadRecoveryAndOnlyRetryResends() = runTest {
var future = open()
val first = port(MockEngine { error("No initial transport") })
val command = first.record(authority, "item", MembershipPort.Kind.FAVORITE, true)
val row = requireNotNull(future.dirtyOperationDao().getById(command.id))
future.dirtyOperationDao().claimMembership(command.id, requireNotNull(row.membershipAuthority), "claim", "dead-process")
future.close(); future = open()
val methods = mutableListOf<HttpMethod>()
val restarted = port(MockEngine { methods += it.method; respond("", HttpStatusCode.NotFound) })
val restarted = port(MockEngine {
methods += it.method
respond("", if (it.method == HttpMethod.Get) HttpStatusCode.NotFound else HttpStatusCode.NoContent)
})
assertEquals(MembershipPort.Disposition.NEEDS_RECONCILIATION,
restarted.projection(authority, "item", MembershipPort.Kind.FAVORITE)?.disposition)
assertTrue(restarted.dispatch().isEmpty())
Expand All @@ -199,6 +202,10 @@ class DormantMembershipTest {
assertNotNull(future.dirtyOperationDao().getById(command.id))
assertEquals(0, future.dirtyOperationDao().runnableLegacyCountForScope("s", "", "p"))
assertEquals(listOf(HttpMethod.Get), methods)
assertTrue(restarted.retry(command).mayPublish)
assertEquals(MembershipPort.Disposition.ACKNOWLEDGED,
restarted.projection(authority, "item", MembershipPort.Kind.FAVORITE)?.disposition)
assertEquals(listOf(HttpMethod.Get, HttpMethod.Get, HttpMethod.Put), methods)
}

@Test fun dispatcherLimitBoundsRequestsAndOldIdentityAckDoesNotPublish() = runTest {
Expand Down
Loading