From c93818eb7d097444fd71e369840ccff686ff44e7 Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 02:41:24 +0000 Subject: [PATCH 1/5] android: fix 409 idempotency_in_flight key drop and unify failure classification --- .../features/bots/AidenBotEditorScreen.kt | 5 +- .../bots/AidenBotGeneratedAvatarLifecycle.kt | 8 +- .../bots/AidenBotOpenWorkController.kt | 29 ++- .../features/bots/AidenBotPeersController.kt | 13 +- .../features/bots/AidenBotResumeController.kt | 19 +- .../bots/AidenBotRoutineModelsController.kt | 10 +- .../bots/AidenBotSessionController.kt | 32 ++- .../features/bots/AidenBotWatchController.kt | 11 +- .../bots/AidenDurablePendingMutation.kt | 49 ++++ .../features/chat/AidenChatFork.kt | 4 +- .../AidenScheduledRunIdempotencyKeys.kt | 23 +- .../AidenOnTheGo/models/AidenNewWorktree.kt | 15 +- .../AidenRemoteFailureClassification.kt | 146 +++++++++++ .../AidenOnTheGo/AidenScheduledTaskTest.kt | 20 ++ .../bots/AidenBotOpenWorkControllerTest.kt | 57 +++++ .../bots/AidenBotPeersControllerTest.kt | 26 ++ .../AidenBotRoutineModelsControllerTest.kt | 26 ++ .../bots/AidenBotSessionControllerTest.kt | 8 +- .../bots/AidenBotWatchControllerTest.kt | 22 ++ .../AidenRemoteFailureClassificationTest.kt | 228 ++++++++++++++++++ 20 files changed, 670 insertions(+), 81 deletions(-) create mode 100644 android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenDurablePendingMutation.kt create mode 100644 android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt create mode 100644 android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotEditorScreen.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotEditorScreen.kt index b693e527d8..b708bfbe52 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotEditorScreen.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotEditorScreen.kt @@ -31,11 +31,12 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import sbtbiswas.AidenOnTheGo.R -import sbtbiswas.AidenOnTheGo.features.scheduled.aidenScheduledRunFailureIsAmbiguous import sbtbiswas.AidenOnTheGo.features.remote.AidenRemoteCoordinator import sbtbiswas.AidenOnTheGo.features.shared.AidenModelPickerField import sbtbiswas.AidenOnTheGo.features.shared.AidenModelRoute import sbtbiswas.AidenOnTheGo.models.* +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import sbtbiswas.AidenOnTheGo.ui.theme.AidenPrimaryButton import sbtbiswas.AidenOnTheGo.ui.theme.AidenTheme import sbtbiswas.AidenOnTheGo.ui.theme.AidenUi @@ -171,7 +172,7 @@ class AidenBotCreateAttempts( */ fun failed(attempt: AidenBotCreateAttempt, error: Throwable) { if (error is AidenBotChatActivityUnreachable) return - uncertain = if (aidenScheduledRunFailureIsAmbiguous(error)) attempt else null + uncertain = if (AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER)) attempt else null } /** The Mac made [attempt]'s Bot: another Create with the same answers is another Bot. */ diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt index dc307e656e..b7f4b15e0f 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt @@ -34,6 +34,8 @@ import sbtbiswas.AidenOnTheGo.models.AidenBotSummary import sbtbiswas.AidenOnTheGo.models.AidenBotSemanticAvatar import sbtbiswas.AidenOnTheGo.networking.AidenRemoteClient import sbtbiswas.AidenOnTheGo.persistence.AidenBotCache +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import sbtbiswas.AidenOnTheGo.ui.theme.AidenActivityDot import java.io.ByteArrayOutputStream import java.security.MessageDigest @@ -61,7 +63,11 @@ fun aidenBotAvatarExpectedRevision(bot: AidenBotDetail): String = bot.avatar.asset?.assetRevision ?: bot.revision fun aidenBotAvatarMutationFailureIsAmbiguous(error: Throwable): Boolean { - return error !is AidenBotGeneratedAvatarError.Unavailable + if (error is AidenBotGeneratedAvatarError.Unavailable) return false + return AidenRemoteFailureClassification.isAmbiguous( + error, + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + ) } object AidenBotGeneratedAvatarNormalizer { diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkController.kt index ccec8a3aca..5d673eca43 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkController.kt @@ -10,7 +10,7 @@ import kotlinx.coroutines.flow.update import kotlinx.serialization.Serializable import sbtbiswas.AidenOnTheGo.models.* import sbtbiswas.AidenOnTheGo.persistence.AidenBotWatchJournal -import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID interface AidenBotOpenWorkTransport { @@ -58,7 +58,7 @@ class AidenBotOpenWorkController(private val transport: AidenBotOpenWorkTranspor check(journal.replace(persisted, encoded)) { "Another window changed the saved request" } persisted = encoded true - } catch (_: Exception) { _state.update { it.copy(problem = AidenOpenWorkProblem.STORAGE) }; false } + } catch (_: Exception) { storageBlocked = true; _state.update { it.copy(problem = AidenOpenWorkProblem.STORAGE) }; false } private fun settle(snapshot: AidenOpenWorkSnapshot): Boolean { val attempt = _state.value.pending ?: return false val mutation = attempt.mutation @@ -131,7 +131,9 @@ class AidenBotOpenWorkController(private val transport: AidenBotOpenWorkTranspor if (_state.value.pending != null || !canWrite() || now() >= option.expiresAt || _state.value.snapshot?.undo?.contains(option) != true || hasPendingStop(option.itemId)) return perform(AidenOpenWorkAttempt(AidenOpenWorkMutation(uuid(),AidenOpenWorkAction.UNDO,option.expectedRevision,undoOf=option.mutationId),now())) } - fun retryAllowed(): Boolean = _state.value.pending?.let { it.mutation.action.isStop || now() - it.startedAt in 0 until 23 * 60 * 60 * 1000L } == true + fun retryAllowed(): Boolean = _state.value.pending?.let { + AidenDurablePendingMutation.isRetryAllowed(it.startedAt, now(), exempt = it.mutation.action.isStop) + } == true suspend fun retry() { val pending = _state.value.pending ?: return if (!retryAllowed()) { _state.update { it.copy(problem = AidenOpenWorkProblem.EXPIRED) }; return } @@ -170,10 +172,23 @@ class AidenBotOpenWorkController(private val transport: AidenBotOpenWorkTranspor } } catch (e: CancellationException) { _state.update { it.copy(problem = AidenOpenWorkProblem.UNCERTAIN) }; throw e } catch (e: Exception) { - val server = e as? AidenRemoteClientException.Server - val definite = server?.statusCode in listOf(400,401,403,404,409,422) - if (!previous && definite && persist(pending=null)) _state.update { it.copy(pending=null) } - _state.update { it.copy(problem = if (it.pending != null) AidenOpenWorkProblem.UNCERTAIN else AidenOpenWorkProblem.FAILED) } + val settlement = AidenDurablePendingMutation.settleFailure( + error = e, + previouslyUnknown = previous, + policy = AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL + ) + val definite = settlement == AidenDurableFailureSettlement.CLEAR_DEFINITE + val cleared = definite && persist(pending = null) + if (cleared) _state.update { it.copy(pending = null) } + _state.update { + it.copy( + problem = when { + storageBlocked || (definite && !cleared) -> AidenOpenWorkProblem.STORAGE + it.pending != null -> AidenOpenWorkProblem.UNCERTAIN + else -> AidenOpenWorkProblem.FAILED + } + ) + } } finally { _state.update { it.copy(busy=false) } } load() } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersController.kt index 6ed6f1fb9f..65d2076b11 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersController.kt @@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.* import kotlinx.serialization.Serializable import sbtbiswas.AidenOnTheGo.models.* import sbtbiswas.AidenOnTheGo.persistence.AidenBotWatchJournal +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID interface AidenBotPeersTransport { @@ -94,7 +95,7 @@ class AidenBotPeersController(val botId:String,private val transport:AidenBotPee start(AidenPeerMutation(AidenPeerAction.REVOKE,botId,uuid(),revision,pairId=pair.id,pairRevision=pair.revision)) } private suspend fun start(request:AidenPeerMutation){val attempt=AidenPeerAttempt(request,now());if(retain(_state.value.copy(pending=attempt)))send(attempt,false)} - fun retryAllowed()=_state.value.pending?.let{now()-it.startedAt in 0 until RETRY_MS}==true + fun retryAllowed()=_state.value.pending?.let{AidenDurablePendingMutation.isRetryAllowed(it.startedAt,now())}==true suspend fun retry(){val p=_state.value.pending ?: return;if(!retryAllowed()){_state.update{it.copy(problem=AidenRoutineControlProblem.EXPIRED)};return};send(p,true)} private suspend fun send(p:AidenPeerAttempt,unknown:Boolean){ if(!current() || !canRead() || !canWrite() || storageBlocked || _state.value.busy)return @@ -105,7 +106,7 @@ class AidenBotPeersController(val botId:String,private val transport:AidenBotPee if(r.ok){check(r.mutationId==p.request.mutationId);retain(settled(requireNotNull(r.snapshot),p.request.action==AidenPeerAction.DESCRIBE))} else {r.snapshot?.let(::apply);if(_state.value.pending!=null){val keep=unknown || r.code==AidenPeerError.UNAVAILABLE;retain(_state.value.copy(pending=if(keep)p else null,needsReview=_state.value.needsReview || r.code==AidenPeerError.CONFLICT,problem=if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED,message=r.error))}} }catch(e:CancellationException){if(current())_state.update{it.copy(problem=AidenRoutineControlProblem.UNCERTAIN)};throw e} - catch(e:Exception){if(current()){val keep=unknown || aidenBotResumeFailureIsAmbiguous(e);retain(_state.value.copy(pending=if(keep)p else null,problem=if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED))}} + catch(e:Exception){if(current()){val keep=AidenDurablePendingMutation.settleFailure(e,unknown,AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)==AidenDurableFailureSettlement.RETAIN_UNCERTAIN;retain(_state.value.copy(pending=if(keep)p else null,problem=if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED))}} finally{if(current())_state.update{it.copy(busy=false)}} } suspend fun openExchange(id:String){ @@ -124,7 +125,7 @@ class AidenBotPeersController(val botId:String,private val transport:AidenBotPee if(unknown && !retainStop(p))return val g=++generation;_state.update{it.copy(busy=true,loading=false,problem=null,message=null)} try { - if(now()-p.startedAt !in 0 until RETRY_MS) { + if(!AidenDurablePendingMutation.isRetryAllowed(p.startedAt,now())) { val row=transport.detail(p.request.exchangeId) if(!current() || !canReadExchanges() || !canWrite() || g!=generation)return applyDetail(row) @@ -134,9 +135,9 @@ class AidenBotPeersController(val botId:String,private val transport:AidenBotPee val r=transport.stop(p.request);if(!current() || !canReadExchanges())return r.exchange?.let{check(it.belongsTo(botId) && it.id==p.request.exchangeId)} if(r.ok){check(r.mutationId==p.request.mutationId);applyDetail(requireNotNull(r.exchange));if(_state.value.pendingStop!=null)_state.update{it.copy(problem=AidenRoutineControlProblem.UNCERTAIN,message="Stop is pending. Check again for the host’s acknowledgement.")}} - else {r.exchange?.let(::applyDetail);if(_state.value.pendingStop!=null){val keep=unknown || r.code==AidenPeerError.UNAVAILABLE;if(!keep)retainStop(null);_state.update{it.copy(problem=if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED,message=r.error)}}} + else {r.exchange?.let(::applyDetail);if(_state.value.pendingStop!=null){val keep=unknown || r.code==AidenPeerError.UNAVAILABLE;if(!keep)retainStop(null);_state.update{it.copy(problem=if(storageBlocked)AidenRoutineControlProblem.STORAGE else if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED,message=r.error)}}} }catch(e:CancellationException){if(current())_state.update{it.copy(problem=AidenRoutineControlProblem.UNCERTAIN)};throw e} - catch(e:Exception){if(current()){val keep=unknown || aidenBotResumeFailureIsAmbiguous(e);if(!keep)retainStop(null);_state.update{it.copy(problem=if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED)}}} + catch(e:Exception){if(current()){val keep=AidenDurablePendingMutation.settleFailure(e,unknown,AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)==AidenDurableFailureSettlement.RETAIN_UNCERTAIN;if(!keep)retainStop(null);_state.update{it.copy(problem=if(storageBlocked)AidenRoutineControlProblem.STORAGE else if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED)}}} finally{if(current())_state.update{it.copy(busy=false)}} } suspend fun showEvidence(kind:AidenOpenWorkEvidenceKind){ @@ -148,7 +149,7 @@ class AidenBotPeersController(val botId:String,private val transport:AidenBotPee } fun closeEvidence(){generation++;_state.update{it.copy(evidence=null,loading=false)}} companion object { - const val RETRY_MS=23*60*60*1000L + const val RETRY_MS=AidenDurablePendingMutation.RETRY_WINDOW_MS fun stopMessage(receipt:AidenPeerStopReceipt)=when(receipt.state){AidenPeerStopState.STOPPED->"The host acknowledged Stop. Earlier effects may remain.";AidenPeerStopState.NOT_RUNNING->"The linked work is no longer running.";AidenPeerStopState.BLOCKED->"Stop was refused. The work remains unfinished.";else->"Stop is pending. Check again for the host’s acknowledgement."} } } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeController.kt index 2c0483cbcb..d87b1aec15 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeController.kt @@ -7,7 +7,8 @@ import kotlinx.coroutines.flow.update import kotlinx.serialization.Serializable import sbtbiswas.AidenOnTheGo.models.* import sbtbiswas.AidenOnTheGo.persistence.AidenBotWatchJournal -import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID interface AidenBotResumeTransport { @@ -15,16 +16,8 @@ interface AidenBotResumeTransport { suspend fun resume(key: UUID, request: AidenBotResumeRequest): AidenBotSessionStateView } /** A status or retryable flag alone cannot prove that Resume had no effect. */ -internal fun aidenBotResumeFailureIsAmbiguous(error: Exception): Boolean { - if(error is AidenRemoteClientException.Server) { - val beforeEffectCodes=setOf("invalid_request","payload_too_large","authentication_required","credential_revoked", - "capability_denied","server_identity_changed","not_found","bot_archived","operation_stale","bot_paused", - "idempotency_conflict","idempotency_capacity","rate_limited") - if(error.body.code.rawValue !in beforeEffectCodes) return true - } - if(error is AidenRemoteClientException.UnexpectedStatus) return true - return aidenBotMessageFailureIsAmbiguous(error) -} +internal fun aidenBotResumeFailureIsAmbiguous(error: Throwable): Boolean = + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) @Serializable data class AidenBotResumeAttempt(val key: String, val request: AidenBotResumeRequest, val startedAt: Long) { init { AidenOpenWorkWire.uuid(key); check(startedAt>=0) } } @@ -86,7 +79,7 @@ class AidenBotResumeController(private val transport: AidenBotResumeTransport, p if(attempt.request.acknowledgeUnknownCost==true && !supportsPreflight()) { _state.update{it.copy(problem=AidenRoutineControlProblem.UNCERTAIN)};return null } - if(now()-attempt.startedAt !in 0 until 23*60*60*1000L) { _state.update { it.copy(problem=AidenRoutineControlProblem.EXPIRED) }; return null } + if(!AidenDurablePendingMutation.isRetryAllowed(attempt.startedAt,now())) { _state.update { it.copy(problem=AidenRoutineControlProblem.EXPIRED) }; return null } if(previouslyUnknown && !retain(attempt)) return null _state.update { it.copy(busy=true,problem=null) } try { @@ -96,7 +89,7 @@ class AidenBotResumeController(private val transport: AidenBotResumeTransport, p } catch(e: CancellationException) { if(current()) _state.update { it.copy(problem=AidenRoutineControlProblem.UNCERTAIN) }; throw e } catch(e: Exception) { if(!current()) return null - val unknown=previouslyUnknown || aidenBotResumeFailureIsAmbiguous(e) + val unknown=AidenDurablePendingMutation.settleFailure(e,previouslyUnknown,AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)==AidenDurableFailureSettlement.RETAIN_UNCERTAIN if(!unknown) retain(null) _state.update { it.copy(problem=if(storageBlocked)AidenRoutineControlProblem.STORAGE else if(unknown)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED) } } finally { _state.update { it.copy(busy=false) } } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsController.kt index 8bc71974a0..b945e19e44 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsController.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.update import kotlinx.serialization.Serializable import sbtbiswas.AidenOnTheGo.models.* import sbtbiswas.AidenOnTheGo.persistence.AidenBotWatchJournal +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID interface AidenBotRoutineModelsTransport { @@ -114,7 +115,7 @@ class AidenBotRoutineModelsController(val botId: String, private val routineId: val attempt=AidenRoutineModelAttempt(AidenRoutineModelSave(botId,routineId,uuid(),ui.baseline!!.revision,ui.catalog!!.revision,ui.draft!!),now()) if(retain(ui.copy(pending=attempt))) send(attempt,false) } - fun retryAllowed()=_state.value.pending?.let { now()-it.startedAt in 0 until 23*60*60*1000L }==true + fun retryAllowed()=_state.value.pending?.let { AidenDurablePendingMutation.isRetryAllowed(it.startedAt,now()) }==true suspend fun retry() { val attempt=_state.value.pending ?: return if(!retryAllowed()) { _state.update { it.copy(problem=AidenRoutineControlProblem.EXPIRED) }; return } @@ -143,8 +144,11 @@ class AidenBotRoutineModelsController(val botId: String, private val routineId: } } catch(e: CancellationException) { if(current()) _state.update { it.copy(problem=AidenRoutineControlProblem.UNCERTAIN) }; throw e } catch(e: Exception) { - if(current() && canRead()) retain(_state.value.copy(pending=if(previouslyUnknown || aidenBotMessageFailureIsAmbiguous(e))attempt else null, - problem=if(previouslyUnknown || aidenBotMessageFailureIsAmbiguous(e))AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED)) + if(current() && canRead()) { + val keep=AidenDurablePendingMutation.settleFailure(e,previouslyUnknown,AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)==AidenDurableFailureSettlement.RETAIN_UNCERTAIN + retain(_state.value.copy(pending=if(keep)attempt else null, + problem=if(keep)AidenRoutineControlProblem.UNCERTAIN else AidenRoutineControlProblem.FAILED)) + } } finally { _state.update { it.copy(busy=false) } } } } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt index 121fcfb979..1770c8ea0d 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt @@ -19,6 +19,8 @@ import sbtbiswas.AidenOnTheGo.networking.AidenRemoteClient import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteCapability import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteErrorCode +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID /** The routes a durable Bot chat uses. [AidenRemoteClient] provides them on a revision-25 Mac. */ @@ -303,8 +305,8 @@ class AidenBotActionKeys(private val newKey: () -> UUID = UUID::randomUUID) { keys.remove(action) } - /** Ends [action] when [error] is an answer from the Mac; keeps its key when the outcome is unknown. */ - fun failed(action: String, error: Exception) { + /** Ends [action] when [error] is a definite refusal from the Mac; keeps its key when the outcome is unknown. */ + fun failed(action: String, error: Throwable) { if (aidenBotMacAnswered(error)) complete(action) } } @@ -313,8 +315,14 @@ class AidenBotActionKeys(private val newKey: () -> UUID = UUID::randomUUID) { fun aidenBotFilesChatId(botId: String, conversations: List): String? = aidenCanonicalBotConversations(conversations).firstOrNull { it.botId == botId }?.chatId -/** True when the Mac sent an HTTP answer, so a retry is a new action rather than a replay. */ -fun aidenBotMacAnswered(error: Exception): Boolean = error is AidenRemoteClientException.Server +/** + * True when the host returned a definite refusal that settled or rejected the action, so a retry + * should start a fresh request rather than replay the same `Idempotency-Key`. Ambiguous outcomes + * (`409 idempotency_in_flight`, `5xx`, `408`, `429`, transport/parse failures, cancellation) keep + * the key. + */ +fun aidenBotMacAnswered(error: Throwable): Boolean = + !AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER) /** Where a connect card's action stands on this phone. */ enum class AidenBotConnectRequestPhase { IDLE, SENDING, SENT, FAILED } @@ -371,18 +379,8 @@ fun aidenBotOutboxFailureStep( } /** True when a message request may have reached the Mac, so the next attempt must reuse its key. */ -fun aidenBotMessageFailureIsAmbiguous(error: Exception): Boolean = when (error) { - is AidenRemoteClientException.Server -> error.statusCode >= 500 || error.statusCode == 408 || error.statusCode == 429 || - // The Mac is still working on the first attempt: its outcome is unknown. - (error.statusCode == 409 && error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT) - is AidenRemoteClientException.UnexpectedStatus -> error.statusCode >= 500 || error.statusCode == 408 || error.statusCode == 429 - is AidenRemoteClientException.MissingCredential, - is AidenRemoteClientException.MissingTrustConfiguration, - is AidenRemoteClientException.InstallationChanged, - is AidenRemoteClientException.InvalidEndpoint -> false - // A dropped connection or an unreadable answer: the Mac may have taken it. - else -> true -} +fun aidenBotMessageFailureIsAmbiguous(error: Throwable): Boolean = + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER) /** 401 or 403, or a pairing that's gone: this phone no longer reaches this Bot. */ fun aidenBotLostAccess(error: Exception): Boolean = when (error) { @@ -1931,7 +1929,7 @@ class AidenBotSessionController( if (accessRequestWrites == writes) _state.update { it.copy(session = it.session?.copy(accessRequest = shown)) } throw error } catch (error: Exception) { - if (error is AidenRemoteClientException.Server && error.statusCode < 500) keys.complete(action) + keys.failed(action, error) val expired = (error as? AidenRemoteClientException.Server)?.body?.code == AidenRemoteErrorCode.ACCESS_REQUEST_EXPIRED _state.update { state -> val session = state.session diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt index b742210733..1f6284b84b 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.update import sbtbiswas.AidenOnTheGo.models.* import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteErrorCode +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID interface AidenBotWatchTransport { @@ -219,11 +220,15 @@ class AidenBotWatchController(private val transport: AidenBotWatchTransport, pri } catch (e: Exception) { val server = e as? AidenRemoteClientException.Server val conflict = server?.body?.code == AidenRemoteErrorCode.REVISION_CONFLICT - val definite = conflict || (server != null && server.statusCode in listOf(400, 401, 403, 404, 422) && - server.body.code !in listOf(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT, AidenRemoteErrorCode.IDEMPOTENCY_CONFLICT)) + val settlement = AidenDurablePendingMutation.settleFailure( + error = e, + previouslyUnknown = wasPending, + policy = AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + ) + val definite = settlement == AidenDurableFailureSettlement.CLEAR_DEFINITE val permissionDenied = server?.statusCode in listOf(401, 403) // A later guard failure cannot establish whether the original lost request ran. - val cleared = !wasPending && definite && persist(attempt = null) + val cleared = definite && persist(attempt = null) if (cleared) pending = null _state.update { it.copy(pending = pending != null, error = when { permissionDenied -> AidenBotWatchError.PERMISSION diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenDurablePendingMutation.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenDurablePendingMutation.kt new file mode 100644 index 0000000000..8730ae5345 --- /dev/null +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenDurablePendingMutation.kt @@ -0,0 +1,49 @@ +package sbtbiswas.AidenOnTheGo.features.bots + +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy + +/** Outcome of classifying a failed durable Bot mutation transport call. */ +enum class AidenDurableFailureSettlement { + /** Outcome may have committed (or was already uncertain): retain pending attempt & key. */ + RETAIN_UNCERTAIN, + /** First attempt failed with a proven before-effect refusal: safe to clear pending attempt. */ + CLEAR_DEFINITE +} + +/** + * Shared invariants for Android's durable pending-mutation Bot controllers (`Resume`, `Watch`, + * `RoutineModels`, `Peers`, `OpenWork`): + * + * - 23-hour replay window matching the host's 24-hour idempotency ledger with a 1-hour skew margin, + * plus explicit exemption hook (e.g. OpenWork `Stop` / `Stop & Dismiss`). + * - Sticky `previouslyUnknown` protection: once an attempt's outcome is unknown, no later refusal + * can clear it; only a same-key host reply or authoritative read reconciliation may settle it. + * - Strict before-effect refusal classification via [AidenRemoteFailureClassification]. + */ +object AidenDurablePendingMutation { + /** 23 hours: leaves a 1-hour safety margin inside the host's 24-hour idempotency retention. */ + const val RETRY_WINDOW_MS: Long = 23L * 60L * 60L * 1000L + + /** + * Returns `true` while an uncertain attempt started at [startedAtMs] may still be replayed at + * [nowMs]. Clock rollback (`nowMs < startedAtMs`) fails closed unless [exempt] is `true`. + */ + fun isRetryAllowed(startedAtMs: Long, nowMs: Long, exempt: Boolean = false): Boolean = + exempt || (nowMs - startedAtMs in 0L until RETRY_WINDOW_MS) + + /** + * Decides whether a failed transport call must retain the pending attempt or may clear it. + * Once [previouslyUnknown] is `true`, the attempt stays sticky regardless of [error]. + */ + fun settleFailure( + error: Throwable, + previouslyUnknown: Boolean, + policy: AidenRemoteFailurePolicy = AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL + ): AidenDurableFailureSettlement = + if (previouslyUnknown || AidenRemoteFailureClassification.isAmbiguous(error, policy)) { + AidenDurableFailureSettlement.RETAIN_UNCERTAIN + } else { + AidenDurableFailureSettlement.CLEAR_DEFINITE + } +} diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt index 40d1c08451..11bbceade0 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt @@ -6,6 +6,8 @@ import sbtbiswas.AidenOnTheGo.models.AidenChatRole import sbtbiswas.AidenOnTheGo.models.AidenGenerationTimelineStatus import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteErrorCode +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy /** * Which messages offer the fork actions. Mirrors the Mac's rules so the menu @@ -83,7 +85,7 @@ object AidenChatForkErrors { * `internal_error`, so the next attempt needs a fresh key. */ fun isOutcomeUnknown(error: Throwable): Boolean = - serverError(error)?.let { it.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT } ?: true + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT) /** A summary route's 404 or 409 means the summary already changed elsewhere. */ fun isSummaryMovedOn(error: Throwable): Boolean = isNotFound(error) || isRevisionConflict(error) diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/scheduled/AidenScheduledRunIdempotencyKeys.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/scheduled/AidenScheduledRunIdempotencyKeys.kt index ea6a65bf09..67409bc30b 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/scheduled/AidenScheduledRunIdempotencyKeys.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/scheduled/AidenScheduledRunIdempotencyKeys.kt @@ -1,10 +1,7 @@ package sbtbiswas.AidenOnTheGo.features.scheduled -import kotlinx.serialization.SerializationException -import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException -import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteContractException -import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteErrorCode -import java.io.IOException +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy import java.util.UUID /** @@ -30,17 +27,5 @@ class AidenScheduledRunIdempotencyKeys( fun aidenScheduledOperationCanClear(activeRequestId: UUID?, completedRequestId: UUID): Boolean = activeRequestId == completedRequestId -fun aidenScheduledRunFailureIsAmbiguous(error: Throwable): Boolean = when (error) { - is IOException, - is SerializationException, - is AidenRemoteContractException, - is AidenRemoteClientException.InvalidResponse, - is AidenRemoteClientException.Disconnected, - is AidenRemoteClientException.UnexpectedStatus -> true - - is AidenRemoteClientException.Server -> - error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT || - error.body.code == AidenRemoteErrorCode.INTERNAL_ERROR - - else -> false -} +fun aidenScheduledRunFailureIsAmbiguous(error: Throwable): Boolean = + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER) diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt index 99bed81c38..a00692618d 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt @@ -5,7 +5,8 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonObject import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteClientException -import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteErrorCode +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailureClassification +import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteFailurePolicy /** * Contract revision 53 (`chat:new-worktree`): the first message of an empty Workspace chat can @@ -28,13 +29,11 @@ object AidenNewWorktreeRetry { * did with it. An answer this phone could not read spends it too: the Mac would only replay * the same answer under that key. */ - fun spendsKey(error: Throwable): Boolean = when (error) { - is AidenRemoteClientException.Server -> error.body.code != AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT - is AidenRemoteClientException.UnexpectedStatus, - is AidenRemoteClientException.InvalidResponse, - is AidenRemoteClientException.IdempotencyConflict -> true - else -> false - } + fun spendsKey(error: Throwable): Boolean = !AidenRemoteFailureClassification.isAmbiguous( + error, + AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT, + unreadableResponseAmbiguous = false + ) } /** The empty chat, now in its new worktree's workspace, and the worktree's branch. */ diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt new file mode 100644 index 0000000000..9a6e0b8c09 --- /dev/null +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt @@ -0,0 +1,146 @@ +package sbtbiswas.AidenOnTheGo.protocol + +import kotlinx.coroutines.CancellationException + +/** + * Endpoint-contract policies for deciding whether a failed Remote mutation may have taken effect + * on the host (so the client must keep its pending attempt / `Idempotency-Key` for replay or + * authoritative reconciliation) versus a definite refusal that proved no effect occurred or + * settled the key in the host ledger. + */ +enum class AidenRemoteFailurePolicy { + /** + * Strict before-effect refusal allowlist for Bot control and custom-receipt routes + * (`resume`, `open-work`, `peers`, `routine-models`). + * + * Only structured 4xx responses (excluding `408`/`429`) whose error code is on + * [AidenRemoteFailureClassification.BEFORE_EFFECT_REFUSAL_CODES] prove the request had no + * effect. `409 idempotency_in_flight`, `409 internal_error`, unknown `409`s, `400` with + * unrecognized codes, `5xx`, `408`, `429`, unstructured [AidenRemoteClientException.UnexpectedStatus], + * transport/parse failures, and [CancellationException] are all ambiguous. + */ + BEFORE_EFFECT_REFUSAL, + + /** + * Same strict before-effect refusal allowlist as [BEFORE_EFFECT_REFUSAL], plus + * `409 revision_conflict` for routes whose optimistic-concurrency revision check rejects + * stale writes before any effect (`watches`, `avatar`). + */ + BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT, + + /** + * Durable idempotency ledger routes (`executeAidenDurableOperation`) aligned with + * `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json` (`messages`, Bot session + * control actions, scheduled task run-now, Bot create): + * - `5xx`, `408`, `429`, and `409 idempotency_in_flight` are ambiguous (keep key). + * - Other structured 4xx responses (including replayed settled rejections such as + * `409 internal_error` and `409 idempotency_conflict`) settle the key. + * - Unstructured [AidenRemoteClientException.UnexpectedStatus] is ambiguous on `5xx`/`408`/`429`. + * - Transport/parse failures and [CancellationException] are ambiguous (keep key). + */ + CACHED_REJECTION_LEDGER, + + /** + * Durable idempotency ledger routes (`fork`, `continue-in-new-chat`, `new-worktree`) where + * the host caches every structured server rejection under the key for 24 hours: + * - Only `409 idempotency_in_flight`, transport failures, and [CancellationException] keep + * the key; any other structured [AidenRemoteClientException.Server] response spends it. + */ + CACHED_REJECTION_LEDGER_STRICT +} + +object AidenRemoteFailureClassification { + /** + * Structured error codes the host returns strictly before any Bot control or custom-receipt + * mutation effect can commit. + */ + val BEFORE_EFFECT_REFUSAL_CODES: Set = setOf( + AidenRemoteErrorCode.INVALID_REQUEST, + AidenRemoteErrorCode.PAYLOAD_TOO_LARGE, + AidenRemoteErrorCode.AUTHENTICATION_REQUIRED, + AidenRemoteErrorCode.CREDENTIAL_REVOKED, + AidenRemoteErrorCode.CAPABILITY_DENIED, + AidenRemoteErrorCode.SERVER_IDENTITY_CHANGED, + AidenRemoteErrorCode.NOT_FOUND, + AidenRemoteErrorCode.BOT_ARCHIVED, + AidenRemoteErrorCode.OPERATION_STALE, + AidenRemoteErrorCode.BOT_PAUSED, + AidenRemoteErrorCode.IDEMPOTENCY_CONFLICT, + AidenRemoteErrorCode.IDEMPOTENCY_CAPACITY, + AidenRemoteErrorCode.RATE_LIMITED + ) + + private fun isPreSendLocalError(error: Throwable): Boolean = when (error) { + is AidenRemoteClientException.MissingCredential, + is AidenRemoteClientException.MissingTrustConfiguration, + is AidenRemoteClientException.InstallationChanged, + is AidenRemoteClientException.InvalidEndpoint -> true + else -> false + } + + private fun isTransientHttpStatus(statusCode: Int): Boolean = + statusCode >= 500 || statusCode == 408 || statusCode == 429 + + /** + * Returns `true` when [error] leaves the remote mutation outcome unknown under [policy], so + * the caller must retain its pending attempt / `Idempotency-Key`. + * + * Set [unreadableResponseAmbiguous] to `false` only for routes where an unreadable HTTP + * response (`InvalidResponse` / `UnexpectedStatus` / `IdempotencyConflict`) indicates the + * host already answered and would replay that same answer under the same key (e.g. + * `new-worktree`). + */ + fun isAmbiguous( + error: Throwable, + policy: AidenRemoteFailurePolicy, + unreadableResponseAmbiguous: Boolean = true + ): Boolean { + if (error is CancellationException) return true + if (isPreSendLocalError(error)) return false + return when (policy) { + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL -> + isBeforeEffectAmbiguous(error, allowRevisionConflict = false) + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT -> + isBeforeEffectAmbiguous(error, allowRevisionConflict = true) + AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER -> + isCachedRejectionLedgerAmbiguous(error) + AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT -> + isCachedRejectionLedgerStrictAmbiguous(error, unreadableResponseAmbiguous) + } + } + + private fun isBeforeEffectAmbiguous(error: Throwable, allowRevisionConflict: Boolean): Boolean = when (error) { + is AidenRemoteClientException.Server -> { + if (isTransientHttpStatus(error.statusCode) || error.statusCode !in 400..499) { + true + } else { + val allowed = error.body.code in BEFORE_EFFECT_REFUSAL_CODES || + (allowRevisionConflict && error.body.code == AidenRemoteErrorCode.REVISION_CONFLICT) + !allowed + } + } + is AidenRemoteClientException.UnexpectedStatus -> true + else -> true + } + + private fun isCachedRejectionLedgerAmbiguous(error: Throwable): Boolean = when (error) { + is AidenRemoteClientException.Server -> + isTransientHttpStatus(error.statusCode) || + (error.statusCode == 409 && error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT) + is AidenRemoteClientException.UnexpectedStatus -> + isTransientHttpStatus(error.statusCode) + else -> true + } + + private fun isCachedRejectionLedgerStrictAmbiguous( + error: Throwable, + unreadableResponseAmbiguous: Boolean + ): Boolean = when (error) { + is AidenRemoteClientException.Server -> + error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT + is AidenRemoteClientException.UnexpectedStatus, + is AidenRemoteClientException.InvalidResponse, + is AidenRemoteClientException.IdempotencyConflict -> unreadableResponseAmbiguous + else -> true + } +} diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenScheduledTaskTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenScheduledTaskTest.kt index 18aff66067..79ff4320da 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenScheduledTaskTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenScheduledTaskTest.kt @@ -244,11 +244,31 @@ class AidenScheduledTaskTest { assertEquals(first, keys.keyFor("task_1")) keys.failed("task_1", inFlight) assertEquals(first, keys.keyFor("task_1")) + keys.failed("task_1", kotlinx.coroutines.CancellationException("cancelled")) + assertEquals(first, keys.keyFor("task_1")) + keys.failed( + "task_1", + AidenRemoteClientException.Server( + 503, + AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.OPERATION_IN_PROGRESS, "Unavailable", "req_503", true) + ) + ) + assertEquals(first, keys.keyFor("task_1")) keys.failed("task_1", rejected) assertEquals(second, keys.keyFor("task_1")) assertTrue(aidenScheduledRunFailureIsAmbiguous(inFlight)) + assertTrue(aidenScheduledRunFailureIsAmbiguous(kotlinx.coroutines.CancellationException("cancelled"))) assertFalse(aidenScheduledRunFailureIsAmbiguous(rejected)) + assertFalse( + "a 409 internal_error replays a settled ledger rejection", + aidenScheduledRunFailureIsAmbiguous( + AidenRemoteClientException.Server( + 409, + AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.INTERNAL_ERROR, "Replayed rejection", "req_409", false) + ) + ) + ) } @Test diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt index 77e1e054bb..03e9b473c1 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt @@ -148,4 +148,61 @@ class AidenBotOpenWorkControllerTest { assertEquals("9007199254740993123456",c.state.value.evidence!!.submissionId) c.closeEvidence();assertNull(c.state.value.evidence) } + + @Test fun first409InFlightAndUnknown409RetainPendingAcrossRestartWhileDefiniteClears()=runTest { + val ambiguousErrors=listOf( + AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT,"The change may have completed.","req_1",false)), + AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT,"The change may have completed.","req_2",true)), + AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.INTERNAL_ERROR,"Unknown conflict","req_3",false)), + AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode("future_conflict"),"Future conflict","req_4",false)), + AidenRemoteClientException.Server(400,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode("outcome_unknown"),"Outcome unknown","req_5",false)), + AidenRemoteClientException.UnexpectedStatus(400) + ) + for(failure in ambiguousErrors) { + val host=Host();val secure=InMemoryAidenSecureStore();val first=controller(host,secure) + first.load();first.begin(host.view.items.single());first.edit{it.copy(title="Keep on 409")} + host.answer={throw failure} + first.save() + assertNotNull("must retain pending on $failure",first.state.value.pending) + assertEquals(OPEN_NONCE,first.state.value.pending!!.mutation.mutationId) + assertEquals(AidenOpenWorkProblem.UNCERTAIN,first.state.value.problem) + + val restored=AidenBotOpenWorkController(host,{true},{true},journal(secure),{error("Must replay original UUID")},{1000L}) + assertEquals(OPEN_NONCE,restored.state.value.pending!!.mutation.mutationId) + host.answer={m->AidenOpenWorkResult(true,m.mutationId,true,m.id,host.view)} + restored.retry() + assertNull(restored.state.value.pending) + assertEquals(listOf(OPEN_NONCE,OPEN_NONCE),host.writes.map{it.mutationId}) + } + + // A first proven before-effect refusal clears pending and reports FAILED. + val host=Host();val c=controller(host);c.load();c.begin(host.view.items.single());c.edit{it.copy(title="Refused")} + host.answer={throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Denied","req_6",false))} + c.save() + assertNull(c.state.value.pending) + assertEquals(AidenOpenWorkProblem.FAILED,c.state.value.problem) + + // If clearing a first definite refusal fails in storage, STORAGE is preserved and further writes stay blocked. + var failClear=false;var saved:String?=null + val flakyJournal=object:AidenBotWatchJournal { + override fun read():String?=saved + override fun write(record:String?) { + if(failClear) throw IOException("storage locked") + saved=record + } + } + val storageHost=Host() + val storageController=AidenBotOpenWorkController(storageHost,{true},{true},flakyJournal,{OPEN_NONCE},{1000L}) + storageController.load();storageController.begin(storageHost.view.items.single());storageController.edit{it.copy(title="Clear fails")} + storageHost.answer={ + failClear=true + throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Denied","req_7",false)) + } + storageController.save() + assertNotNull(storageController.state.value.pending) + assertEquals(AidenOpenWorkProblem.STORAGE,storageController.state.value.problem) + failClear=false + storageController.retry() + assertEquals("storage-blocked controller must not transmit again",1,storageHost.writes.size) + } } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt index 7d6955ddf3..99401525b9 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt @@ -138,4 +138,30 @@ class AidenBotPeersControllerTest { assertEquals("{malformed",p.journal("bot_planner|stop|exchange_one").read()) } + @Test fun stopClearStorageFailurePreservesStorageProblemAndBlocksFurtherWrites()=runTest { + for(httpFailure in listOf(true,false)) { + val p=Phone();var failClear=false;var savedStop:String?=null + val flakyStopJournal=object:AidenBotWatchJournal { + override fun read():String?=savedStop + override fun write(record:String?) { + if(failClear) throw IOException("stop journal locked") + savedStop=record + } + } + val c=AidenBotPeersController("bot_planner",p.host,{true},{true},{true},p.journal(),{flakyStopJournal},{PEER_NONCE},{p.clock}) + c.openExchange("exchange_one") + p.host.stopping={ + failClear=true + if(httpFailure) throw denied() + else AidenPeerStopResult(false,code=AidenPeerError.NOT_FOUND,error="Gone") + } + c.stop() + assertNotNull(c.state.value.pendingStop) + assertEquals(AidenRoutineControlProblem.STORAGE,c.state.value.problem) + failClear=false + c.retryStop() + assertEquals("storage-blocked stop controller must not retransmit",1,p.host.stops.size) + } + } + } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt index aaa2e2519b..82e1cfd189 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt @@ -102,4 +102,30 @@ class AidenBotRoutineModelsControllerTest { d.save();slow.complete(fresh.view.copy(revision="old",selection=AidenRoutineModelSelection.Inherit));job.join() assertEquals("r2",d.state.value.settings!!.revision);assertEquals(primary,d.state.value.settings!!.selection.primary) } + + @Test fun first409InFlightUnknown409AndUnexpectedStatusRetainPendingWhileFirstDefiniteClears()=runTest { + val ambiguous=listOf( + AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT,"In flight","req_1",false)), + AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.INTERNAL_ERROR,"Unknown","req_2",false)), + AidenRemoteClientException.Server(400,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode("outcome_unknown"),"Unknown","req_3",false)), + AidenRemoteClientException.UnexpectedStatus(400) + ) + for(failure in ambiguous) { + val host=Host();val c=controller(host);c.load();c.select(primary,false) + host.answer={throw failure} + c.save() + assertNotNull("must retain pending on $failure",c.state.value.pending) + assertEquals(AidenRoutineControlProblem.UNCERTAIN,c.state.value.problem) + host.answer={r->AidenRoutineModelResult(true,host.view.copy(revision="r2",selection=r.selection,lastMutationId=r.mutationId),r.mutationId,true)} + c.retry() + assertNull(c.state.value.pending) + assertEquals(listOf(MODEL_NONCE,MODEL_NONCE),host.writes.map{it.mutationId}) + } + + val host=Host();val c=controller(host);c.load();c.select(primary,false) + host.answer={throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Denied","req_4",false))} + c.save() + assertNull(c.state.value.pending) + assertEquals(AidenRoutineControlProblem.FAILED,c.state.value.problem) + } } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt index 18214b30c1..68d650da20 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt @@ -86,7 +86,13 @@ class AidenBotSessionControllerTest { @Test fun sameChoiceUncertainRetryReusesBodyAndKey() = runTest { val body = json.decodeFromJsonElement(AidenRemoteErrorEnvelope.serializer(), accessSection().getValue("expired")).error .copy(code = AidenRemoteErrorCode.INTERNAL_ERROR) - for (failure in listOf(IOException("lost"), AidenRemoteClientException.Server(503, body))) { + val inFlightBody = body.copy(code = AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT) + for (failure in listOf( + IOException("lost"), + AidenRemoteClientException.Server(503, body), + AidenRemoteClientException.Server(409, inFlightBody), + AidenRemoteClientException.Server(429, body.copy(code = AidenRemoteErrorCode.RATE_LIMITED)) + )) { val transport = FakeTransport(accessSession()) val controller = AidenBotSessionController("bot_fixture_01", transport, backgroundScope) controller.refetch() diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchControllerTest.kt index 056fb7cb49..c32e4e03ee 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchControllerTest.kt @@ -275,4 +275,26 @@ class AidenBotWatchControllerTest { answer.complete(watchList()); reading.join() assertFalse(controller.state.value.view!!.watches.single().enabled) } + + @Test fun unknown409Unknown400AndUnexpectedStatusRetainPendingWatchRun() = runTest { + val ambiguous = listOf( + AidenRemoteClientException.Server(409, AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT, "In flight", "req_1", false)), + AidenRemoteClientException.Server(409, AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.INTERNAL_ERROR, "Unknown", "req_2", false)), + AidenRemoteClientException.Server(400, AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode("outcome_unknown"), "Unknown", "req_3", false)), + AidenRemoteClientException.UnexpectedStatus(400) + ) + for (failure in ambiguous) { + val host = Host() + val controller = AidenBotWatchController(host, { true }, { true }, { MUTATION_ID }) + controller.load() + host.runError = failure + controller.run(host.watches.first()) + assertTrue("must retain pending on $failure", controller.state.value.pending) + assertEquals(AidenBotWatchError.UNCERTAIN, controller.state.value.error) + host.runError = null + controller.retry() + assertFalse(controller.state.value.pending) + assertEquals(listOf(MUTATION_ID, MUTATION_ID), host.runs.map { it.mutationId }) + } + } } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt new file mode 100644 index 0000000000..989446bf51 --- /dev/null +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt @@ -0,0 +1,228 @@ +package sbtbiswas.AidenOnTheGo.protocol + +import kotlinx.coroutines.CancellationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import sbtbiswas.AidenOnTheGo.features.bots.AidenBotActionKeys +import sbtbiswas.AidenOnTheGo.features.bots.AidenBotGeneratedAvatarError +import sbtbiswas.AidenOnTheGo.features.bots.AidenDurableFailureSettlement +import sbtbiswas.AidenOnTheGo.features.bots.AidenDurablePendingMutation +import sbtbiswas.AidenOnTheGo.features.bots.aidenBotAvatarMutationFailureIsAmbiguous +import sbtbiswas.AidenOnTheGo.features.bots.aidenBotMacAnswered +import sbtbiswas.AidenOnTheGo.features.bots.aidenBotMessageFailureIsAmbiguous +import sbtbiswas.AidenOnTheGo.features.bots.aidenBotResumeFailureIsAmbiguous +import sbtbiswas.AidenOnTheGo.features.chat.AidenChatForkErrors +import sbtbiswas.AidenOnTheGo.features.scheduled.aidenScheduledRunFailureIsAmbiguous +import sbtbiswas.AidenOnTheGo.models.AidenNewWorktreeRetry +import java.io.File +import java.io.IOException +import java.net.SocketTimeoutException +import java.util.UUID + +class AidenRemoteFailureClassificationTest { + private fun server(status: Int, code: AidenRemoteErrorCode, retryable: Boolean = false) = + AidenRemoteClientException.Server( + statusCode = status, + body = AidenRemoteErrorEnvelope.Body(code, "Server response", "req_test", retryable) + ) + + @Test + fun inFlight409AndCancellationAreAmbiguousAcrossEveryPolicyAndWrapper() { + val inFlight = server(409, AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT, retryable = false) + val inFlightRetryable = server(409, AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT, retryable = true) + val cancelled = CancellationException("cancelled mid-flight") + val lost = IOException("socket closed") + val disconnected = AidenRemoteClientException.Disconnected() + + for (error in listOf(inFlight, inFlightRetryable, cancelled, lost, disconnected)) { + for (policy in AidenRemoteFailurePolicy.entries) { + assertTrue( + "$error must be ambiguous under $policy", + AidenRemoteFailureClassification.isAmbiguous(error, policy) + ) + } + assertTrue("Resume keeps pending on $error", aidenBotResumeFailureIsAmbiguous(error)) + assertTrue("Bot message keeps key on $error", aidenBotMessageFailureIsAmbiguous(error)) + assertFalse("Bot action keys retain on $error", aidenBotMacAnswered(error)) + assertTrue("Scheduled run keeps key on $error", aidenScheduledRunFailureIsAmbiguous(error)) + assertTrue("Chat fork keeps key on $error", AidenChatForkErrors.isOutcomeUnknown(error)) + assertFalse("New worktree keeps key on $error", AidenNewWorktreeRetry.spendsKey(error)) + assertTrue("Avatar mutation is ambiguous on $error", aidenBotAvatarMutationFailureIsAmbiguous(error)) + } + } + + @Test + fun preSendLocalErrorsAreNeverAmbiguousAcrossPolicies() { + val localErrors = listOf( + AidenRemoteClientException.MissingCredential, + AidenRemoteClientException.MissingTrustConfiguration, + AidenRemoteClientException.InstallationChanged, + AidenRemoteClientException.InvalidEndpoint + ) + for (error in localErrors) { + for (policy in AidenRemoteFailurePolicy.entries) { + assertFalse( + "$error never left the device under $policy", + AidenRemoteFailureClassification.isAmbiguous(error, policy) + ) + } + } + assertFalse(aidenBotAvatarMutationFailureIsAmbiguous(AidenBotGeneratedAvatarError.Unavailable)) + } + + @Test + fun strictBeforeEffectAllowlistDistinguishesUnknownConflictsFromProvenRefusals() { + val unknownErrors = listOf( + server(409, AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT), + server(409, AidenRemoteErrorCode.INTERNAL_ERROR), + server(409, AidenRemoteErrorCode("new_resume_recovery")), + server(400, AidenRemoteErrorCode("outcome_unknown")), + server(500, AidenRemoteErrorCode.INTERNAL_ERROR), + server(503, AidenRemoteErrorCode.INTERNAL_ERROR), + server(408, AidenRemoteErrorCode.INVALID_REQUEST), + server(429, AidenRemoteErrorCode.RATE_LIMITED), + AidenRemoteClientException.UnexpectedStatus(400), + AidenRemoteClientException.UnexpectedStatus(409), + AidenRemoteClientException.InvalidResponse() + ) + for (error in unknownErrors) { + assertTrue( + "$error must stay ambiguous under BEFORE_EFFECT_REFUSAL", + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) + ) + assertTrue( + "$error must stay ambiguous under BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT", + AidenRemoteFailureClassification.isAmbiguous( + error, + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + ) + ) + } + + val revisionConflict = server(409, AidenRemoteErrorCode.REVISION_CONFLICT) + assertTrue( + "Resume does not use revision_conflict as a before-effect refusal", + AidenRemoteFailureClassification.isAmbiguous(revisionConflict, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) + ) + assertFalse( + "Watches and Avatar reject stale If-Match before effect", + AidenRemoteFailureClassification.isAmbiguous( + revisionConflict, + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + ) + ) + + val definiteRefusals = listOf( + server(400, AidenRemoteErrorCode.INVALID_REQUEST), + server(401, AidenRemoteErrorCode.AUTHENTICATION_REQUIRED), + server(403, AidenRemoteErrorCode.CAPABILITY_DENIED), + server(404, AidenRemoteErrorCode.NOT_FOUND), + server(409, AidenRemoteErrorCode.OPERATION_STALE), + server(409, AidenRemoteErrorCode.BOT_PAUSED), + server(409, AidenRemoteErrorCode.IDEMPOTENCY_CONFLICT), + server(413, AidenRemoteErrorCode.PAYLOAD_TOO_LARGE), + server(422, AidenRemoteErrorCode.INVALID_REQUEST) + ) + for (error in definiteRefusals) { + assertFalse( + "$error is a proven before-effect refusal", + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) + ) + assertFalse( + "$error is a proven before-effect refusal with revision conflict enabled", + AidenRemoteFailureClassification.isAmbiguous( + error, + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + ) + ) + } + } + + @Test + fun cachedRejectionLedgerMatchesSharedBotOutboxFixtureAndPreservesStrictReplayContract() { + val relative = "protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json" + val root = generateSequence(File(System.getProperty("user.dir")!!).absoluteFile) { it.parentFile } + .first { File(it, relative).isFile } + val rows = Json.parseToJsonElement(File(root, relative).readText()) + .jsonObject.getValue("classification").jsonArray + for (element in rows) { + val row = element.jsonObject + val error = server( + row.getValue("status").jsonPrimitive.int, + AidenRemoteErrorCode(row.getValue("code").jsonPrimitive.content) + ) + val expected = row.getValue("ambiguous").jsonPrimitive.boolean + val name = row.getValue("name").jsonPrimitive.content + assertEquals( + name, + expected, + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER) + ) + assertEquals(name, expected, aidenScheduledRunFailureIsAmbiguous(error)) + } + + // Strict cached-rejection endpoints spend the key on 500 internal_error as well. + val server500 = server(500, AidenRemoteErrorCode.INTERNAL_ERROR) + assertFalse(AidenChatForkErrors.isOutcomeUnknown(server500)) + assertTrue(AidenNewWorktreeRetry.spendsKey(server500)) + assertTrue(AidenNewWorktreeRetry.spendsKey(AidenRemoteClientException.UnexpectedStatus(502))) + assertTrue(AidenNewWorktreeRetry.spendsKey(AidenRemoteClientException.InvalidResponse())) + assertFalse(AidenNewWorktreeRetry.spendsKey(SocketTimeoutException("timeout"))) + assertTrue(AidenChatForkErrors.isOutcomeUnknown(AidenRemoteClientException.InvalidResponse())) + } + + @Test + fun botActionKeysRetainKeyOnInFlight409And5xxAndClearOnDefiniteRefusal() { + val keys = ArrayDeque( + listOf( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222") + ) + ) + val store = AidenBotActionKeys { keys.removeFirst() } + val first = store.key("stop") + store.failed("stop", server(409, AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT)) + assertEquals(first, store.key("stop")) + store.failed("stop", server(503, AidenRemoteErrorCode.INTERNAL_ERROR)) + assertEquals(first, store.key("stop")) + store.failed("stop", server(429, AidenRemoteErrorCode.RATE_LIMITED)) + assertEquals(first, store.key("stop")) + store.failed("stop", server(403, AidenRemoteErrorCode.CAPABILITY_DENIED)) + assertEquals(UUID.fromString("22222222-2222-4222-8222-222222222222"), store.key("stop")) + } + + @Test + fun durablePendingMutationWindowAndPreviouslyUnknownStickiness() { + val start = 10_000L + assertTrue(AidenDurablePendingMutation.isRetryAllowed(start, start)) + assertTrue(AidenDurablePendingMutation.isRetryAllowed(start, start + AidenDurablePendingMutation.RETRY_WINDOW_MS - 1)) + assertFalse(AidenDurablePendingMutation.isRetryAllowed(start, start + AidenDurablePendingMutation.RETRY_WINDOW_MS)) + assertFalse("clock rollback fails closed", AidenDurablePendingMutation.isRetryAllowed(start, start - 1)) + assertTrue("stop exemption overrides expiry", AidenDurablePendingMutation.isRetryAllowed(start, start + AidenDurablePendingMutation.RETRY_WINDOW_MS * 3, exempt = true)) + + val definite = server(403, AidenRemoteErrorCode.CAPABILITY_DENIED) + assertEquals( + AidenDurableFailureSettlement.CLEAR_DEFINITE, + AidenDurablePendingMutation.settleFailure(definite, previouslyUnknown = false) + ) + assertEquals( + AidenDurableFailureSettlement.RETAIN_UNCERTAIN, + AidenDurablePendingMutation.settleFailure(definite, previouslyUnknown = true) + ) + assertEquals( + AidenDurableFailureSettlement.RETAIN_UNCERTAIN, + AidenDurablePendingMutation.settleFailure( + server(409, AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT), + previouslyUnknown = false + ) + ) + } +} From e4f8635c5a1352fa5a454464c60e0dd3f3616bfa Mon Sep 17 00:00:00 2001 From: Sambit Date: Tue, 24 Nov 2026 06:03:09 +0000 Subject: [PATCH 2/5] android: preserve idempotency key on undecodable error envelopes --- .../bots/AidenBotSessionController.kt | 4 +- .../features/chat/AidenChatViewModel.kt | 2 +- .../networking/AidenRemoteClient.kt | 53 ++-- .../protocol/AidenRemoteExceptions.kt | 13 +- .../AidenRemoteFailureClassification.kt | 33 ++- .../bots/AidenBotSessionControllerTest.kt | 8 +- .../AidenRemoteFailureClassificationTest.kt | 248 ++++++++++++++++++ 7 files changed, 321 insertions(+), 40 deletions(-) diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt index 1770c8ea0d..225df49355 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionController.kt @@ -1893,11 +1893,11 @@ class AidenBotSessionController( } catch (error: CancellationException) { throw error } catch (error: Exception) { if (generation != planGeneration || released || planWrites != writes || _state.value.session?.plan != shown) return false - if (error is AidenRemoteClientException.Server && error.statusCode == 409 && error.body.code == AidenRemoteErrorCode.PLAN_EXPIRED) { + if (error is AidenRemoteClientException.Server && error.isDecodedEnvelope && error.statusCode == 409 && error.body.code == AidenRemoteErrorCode.PLAN_EXPIRED) { planKeys.clear() _state.update { it.copy(session = it.session?.copy(plan = null), planError = null) } } else { - if (error is AidenRemoteClientException.Server && error.statusCode < 500) planKeys.remove(action) + if (aidenBotMacAnswered(error)) planKeys.remove(action) _state.update { it.copy(planError = "That answer wasn't sent. Please try again.") } } false diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt index cdbecacbe8..511f363e92 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt @@ -1871,7 +1871,7 @@ class AidenChatViewModel( scheduleRateLimitedSendRetry(attempt, e, session)) { // The Mac was only busy: keep the send and try it again. } else { - if (e is AidenRemoteClientException.Server && AidenDraftSendReconciliation.refusalSettlesSend(e.statusCode, e.body.code)) { + if (e is AidenRemoteClientException.Server && e.isDecodedEnvelope && AidenDraftSendReconciliation.refusalSettlesSend(e.statusCode, e.body.code)) { session?.let { withContext(ioDispatcher) { draftStore.settlePendingSend(attempt.key, it) } } _pendingSend.value = null _isPendingSendRefusedBecauseBusy.value = false diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRemoteClient.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRemoteClient.kt index 593e81efe2..9f074c8cf7 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRemoteClient.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/networking/AidenRemoteClient.kt @@ -237,7 +237,7 @@ class AidenRemoteClient( if (!response.isSuccessful) { val error = parseError(response.code, responseBytes) - if (response.code == 400 && error.code == AidenRemoteErrorCode.INVALID_REQUEST) { + if (response.code == 400 && error.isDecodedEnvelope && error.body.code == AidenRemoteErrorCode.INVALID_REQUEST) { if (deviceType == AidenDeviceType.ANDROID_PHONE || deviceType == AidenDeviceType.ANDROID_TABLET) { throw AidenPairingBootstrapException.AndroidPairingUnsupported } @@ -261,13 +261,12 @@ class AidenRemoteClient( val retryResponse = client.newCall(retryRequest).await() val retryBytes = retryResponse.body?.bytes() ?: throw AidenRemoteClientException.InvalidResponse() if (!retryResponse.isSuccessful) { - val retryError = parseError(retryResponse.code, retryBytes) - throw AidenRemoteClientException.Server(retryResponse.code, retryError) + throw parseError(retryResponse.code, retryBytes) } AidenRawJsonDuplicateKeyScanner.validate(retryBytes) return@withContext jsonParser.decodeFromString(String(retryBytes, Charsets.UTF_8)) } - throw AidenRemoteClientException.Server(response.code, error) + throw error } AidenRawJsonDuplicateKeyScanner.validate(responseBytes) @@ -390,17 +389,31 @@ class AidenRemoteClient( } } - fun parseError(statusCode: Int, bytes: ByteArray): AidenRemoteErrorEnvelope.Body { + fun parseError( + statusCode: Int, + bytes: ByteArray, + retryAfterHeaderSeconds: Int? = null + ): AidenRemoteClientException.Server { return try { AidenRawJsonDuplicateKeyScanner.validate(bytes) val envelope = jsonParser.decodeFromString(String(bytes, Charsets.UTF_8)) - envelope.error + AidenRemoteClientException.Server( + statusCode = statusCode, + body = envelope.error, + retryAfterHeaderSeconds = retryAfterHeaderSeconds, + isDecodedEnvelope = true + ) } catch (_: Exception) { - AidenRemoteErrorEnvelope.Body( - code = AidenRemoteErrorCode.INTERNAL_ERROR, - message = "Aiden Agent returned HTTP status $statusCode.", - requestId = "", - retryable = false + AidenRemoteClientException.Server( + statusCode = statusCode, + body = AidenRemoteErrorEnvelope.Body( + code = AidenRemoteErrorCode.INTERNAL_ERROR, + message = "Aiden Agent returned HTTP status $statusCode.", + requestId = "", + retryable = false + ), + retryAfterHeaderSeconds = retryAfterHeaderSeconds, + isDecodedEnvelope = false ) } } @@ -491,14 +504,14 @@ class AidenRemoteClient( if (maximumResponseBytes != null && bytes.size > maximumResponseBytes) throw AidenRemoteContractException.PayloadTooLarge if (!unchanged && !acceptedStatus.contains(response.code)) { - val errorBody = parseError(response.code, bytes) + val error = parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.retryAfter)) AidenDiagnostics.record( if (response.code == 401 || response.code == 403) AidenDiagnosticArea.AUTHENTICATION else AidenDiagnosticArea.CONNECTION, AidenDiagnosticEvent.REQUEST_FAILED, AidenDiagnosticOutcome.FAILED, if (response.code == 401 || response.code == 403) AidenDiagnosticCode.UNAUTHORIZED else AidenDiagnosticCode.NETWORK ) - throw AidenRemoteClientException.Server(response.code, errorBody, AidenRetryAfter.parseHeader(response.retryAfter)) + throw error } try { @@ -1225,7 +1238,7 @@ class AidenRemoteClient( AidenDiagnosticOutcome.FAILED, if (response.code == 401 || response.code == 403) AidenDiagnosticCode.UNAUTHORIZED else AidenDiagnosticCode.NETWORK ) - throw AidenRemoteClientException.Server(response.code, parseError(response.code, bytes), AidenRetryAfter.parseHeader(response.header("Retry-After"))) + throw parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.header("Retry-After"))) } val contentType = response.header("Content-Type")?.split(";")?.firstOrNull()?.trim()?.lowercase() if (contentType != "image/jpeg" && contentType != "image/png") { @@ -1301,7 +1314,7 @@ class AidenRemoteClient( AidenDiagnosticOutcome.FAILED, if (response.code == 401 || response.code == 403) AidenDiagnosticCode.UNAUTHORIZED else AidenDiagnosticCode.NETWORK ) - throw AidenRemoteClientException.Server(response.code, parseError(response.code, bytes), AidenRetryAfter.parseHeader(response.header("Retry-After"))) + throw parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.header("Retry-After"))) } val contentType = response.header("Content-Type")?.split(";")?.firstOrNull()?.trim()?.lowercase() if (contentType != "text/html") { @@ -1358,7 +1371,7 @@ class AidenRemoteClient( httpClient.newCall(request).await().use { response -> if (!response.isSuccessful) { val bytes = try { response.body.readBounded(1_048_576) } catch (_: Exception) { ByteArray(0) } - throw AidenRemoteClientException.Server(response.code, parseError(response.code, bytes), AidenRetryAfter.parseHeader(response.header("Retry-After"))) + throw parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.header("Retry-After"))) } val mimeType = response.header("Content-Type")?.split(";")?.firstOrNull()?.trim()?.lowercase() if (mimeType == null || mimeType !in AidenBrowserRecordingRecap.MIME_TYPES || @@ -1708,8 +1721,7 @@ class AidenRemoteClient( call.execute().use { response -> if (!response.isSuccessful) { val bytes = response.body?.bytes() ?: ByteArray(0) - val errorBody = parseError(response.code, bytes) - throw AidenRemoteClientException.Server(response.code, errorBody, AidenRetryAfter.parseHeader(response.header("Retry-After"))) + throw parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.header("Retry-After"))) } onOpen(response.header("Aiden-Progress-Resumed") == "true") val stream = response.body?.byteStream() @@ -2758,8 +2770,7 @@ class AidenRemoteClient( val response = httpClient.newCall(request).await() val bytes = response.body?.bytes() ?: ByteArray(0) if (!response.isSuccessful) { - val errorBody = parseError(response.code, bytes) - throw AidenRemoteClientException.Server(response.code, errorBody, AidenRetryAfter.parseHeader(response.header("Retry-After"))) + throw parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.header("Retry-After"))) } val contentType = response.header("Content-Type")?.split(";")?.firstOrNull()?.trim()?.lowercase() @@ -2796,7 +2807,7 @@ class AidenRemoteClient( httpClient.newCall(request).await().use { response -> if (!response.isSuccessful) { val bytes = try { response.body.readBounded(1_048_576) } catch (_: Exception) { ByteArray(0) } - throw AidenRemoteClientException.Server(response.code, parseError(response.code, bytes), AidenRetryAfter.parseHeader(response.header("Retry-After"))) + throw parseError(response.code, bytes, AidenRetryAfter.parseHeader(response.header("Retry-After"))) } val contentType = response.header("Content-Type")?.split(";")?.firstOrNull()?.trim()?.lowercase() if (contentType !in AidenBotSessionWire.SHARED_IMAGE_MIME_TYPES || diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteExceptions.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteExceptions.kt index e5aa8a50bb..2e2b6ef1a7 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteExceptions.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteExceptions.kt @@ -70,18 +70,23 @@ sealed class AidenRemoteClientException(message: String, cause: Throwable? = nul /** * [retryAfterHeaderSeconds] is the response's HTTP `Retry-After` * delta-seconds, when it sent a usable one. + * [isDecodedEnvelope] is `true` only when [body] was genuinely decoded from a valid + * `AidenRemoteErrorEnvelope` JSON payload, and `false` when the error body was malformed, + * contained duplicate keys, or failed envelope decoding and had to be synthesized. */ data class Server( val statusCode: Int, val body: AidenRemoteErrorEnvelope.Body, val retryAfterHeaderSeconds: Int? = null, + val isDecodedEnvelope: Boolean = true, ) : AidenRemoteClientException(body.message) { val isCredentialRevoked: Boolean - get() = statusCode == 401 || statusCode == 403 || body.code == AidenRemoteErrorCode.CREDENTIAL_REVOKED + get() = statusCode == 401 || statusCode == 403 || + (isDecodedEnvelope && body.code == AidenRemoteErrorCode.CREDENTIAL_REVOKED) /** A 429 the server marked `retryable`: refused before it ran, so it can be sent again. */ val isRetryableRateLimit: Boolean - get() = statusCode == 429 && body.retryable + get() = statusCode == 429 && isDecodedEnvelope && body.retryable /** * The wait a 429 asked for: `details.retryAfterSeconds` first, then @@ -91,7 +96,9 @@ sealed class AidenRemoteClientException(message: String, cause: Throwable? = nul val retryAfterSeconds: Int? get() { if (statusCode != 429) return null - val raw = body.details?.retryAfterSeconds ?: retryAfterHeaderSeconds ?: return null + val raw = (if (isDecodedEnvelope) body.details?.retryAfterSeconds else null) + ?: retryAfterHeaderSeconds + ?: return null return raw.coerceIn(AidenRetryAfter.BOUNDS_SECONDS) } } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt index 9a6e0b8c09..878c7ce0f1 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt @@ -33,18 +33,22 @@ enum class AidenRemoteFailurePolicy { * `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json` (`messages`, Bot session * control actions, scheduled task run-now, Bot create): * - `5xx`, `408`, `429`, and `409 idempotency_in_flight` are ambiguous (keep key). - * - Other structured 4xx responses (including replayed settled rejections such as - * `409 internal_error` and `409 idempotency_conflict`) settle the key. - * - Unstructured [AidenRemoteClientException.UnexpectedStatus] is ambiguous on `5xx`/`408`/`429`. - * - Transport/parse failures and [CancellationException] are ambiguous (keep key). + * - Other structured 4xx responses with a genuinely decoded error envelope (including + * replayed settled rejections such as `409 internal_error` and `409 idempotency_conflict`) + * settle the key. + * - Unreadable/malformed error envelopes ([AidenRemoteClientException.Server.isDecodedEnvelope] + * == `false`), unstructured [AidenRemoteClientException.UnexpectedStatus], transport/parse + * failures, and [CancellationException] are ambiguous (keep key), because an unreadable HTTP + * 409 may have been `409 idempotency_in_flight`. */ CACHED_REJECTION_LEDGER, /** * Durable idempotency ledger routes (`fork`, `continue-in-new-chat`, `new-worktree`) where * the host caches every structured server rejection under the key for 24 hours: - * - Only `409 idempotency_in_flight`, transport failures, and [CancellationException] keep - * the key; any other structured [AidenRemoteClientException.Server] response spends it. + * - `409 idempotency_in_flight`, unreadable/malformed error envelopes (including any + * undecodable HTTP 409), transport failures, and [CancellationException] keep the key; + * any other genuinely decoded [AidenRemoteClientException.Server] response spends it. */ CACHED_REJECTION_LEDGER_STRICT } @@ -111,7 +115,7 @@ object AidenRemoteFailureClassification { private fun isBeforeEffectAmbiguous(error: Throwable, allowRevisionConflict: Boolean): Boolean = when (error) { is AidenRemoteClientException.Server -> { - if (isTransientHttpStatus(error.statusCode) || error.statusCode !in 400..499) { + if (!error.isDecodedEnvelope || isTransientHttpStatus(error.statusCode) || error.statusCode !in 400..499) { true } else { val allowed = error.body.code in BEFORE_EFFECT_REFUSAL_CODES || @@ -125,10 +129,10 @@ object AidenRemoteFailureClassification { private fun isCachedRejectionLedgerAmbiguous(error: Throwable): Boolean = when (error) { is AidenRemoteClientException.Server -> - isTransientHttpStatus(error.statusCode) || + !error.isDecodedEnvelope || + isTransientHttpStatus(error.statusCode) || (error.statusCode == 409 && error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT) - is AidenRemoteClientException.UnexpectedStatus -> - isTransientHttpStatus(error.statusCode) + is AidenRemoteClientException.UnexpectedStatus -> true else -> true } @@ -137,8 +141,13 @@ object AidenRemoteFailureClassification { unreadableResponseAmbiguous: Boolean ): Boolean = when (error) { is AidenRemoteClientException.Server -> - error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT - is AidenRemoteClientException.UnexpectedStatus, + if (!error.isDecodedEnvelope) { + unreadableResponseAmbiguous || error.statusCode == 409 + } else { + error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT + } + is AidenRemoteClientException.UnexpectedStatus -> + unreadableResponseAmbiguous || error.statusCode == 409 is AidenRemoteClientException.InvalidResponse, is AidenRemoteClientException.IdempotencyConflict -> unreadableResponseAmbiguous else -> true diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt index 68d650da20..a9a4b4ee29 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt @@ -32,6 +32,7 @@ import org.junit.Test import org.junit.rules.TemporaryFolder import sbtbiswas.AidenOnTheGo.features.shared.activitymarks.AidenActivityMarkKind import sbtbiswas.AidenOnTheGo.models.* +import sbtbiswas.AidenOnTheGo.networking.AidenRemoteClient import sbtbiswas.AidenOnTheGo.peerFixture import sbtbiswas.AidenOnTheGo.protocol.AidenRemoteCapability import java.time.Instant @@ -221,7 +222,12 @@ class AidenBotSessionControllerTest { controller.stopFollowing() } @Test fun sameDecisionUnknownRetryKeepsKeyAndDifferentDecisionSendsNewBody() = runTest { - for (failure in listOf(IOException("lost"), planError(503))) { + val inFlight409 = AidenRemoteClientException.Server( + 409, + AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT, "In flight", "req_in_flight", true) + ) + val malformed409 = AidenRemoteClient.parseError(409, "{\"error\":{\"code\":\"idempotency_in_flight\"".toByteArray(Charsets.UTF_8)) + for (failure in listOf(IOException("lost"), planError(503), inFlight409, malformed409)) { val initial = planSession(); val transport = FakeTransport(initial) val controller = AidenBotSessionController(initial.botId, transport, backgroundScope, plansSupported = true) controller.refetch(); transport.planFailure = failure diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt index 989446bf51..bc3d4ab136 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt @@ -1,18 +1,29 @@ package sbtbiswas.AidenOnTheGo.protocol import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json import kotlinx.serialization.json.boolean import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue +import org.junit.Assert.fail import org.junit.Test +import sbtbiswas.AidenOnTheGo.auth.InMemoryAidenSecureStore import sbtbiswas.AidenOnTheGo.features.bots.AidenBotActionKeys import sbtbiswas.AidenOnTheGo.features.bots.AidenBotGeneratedAvatarError +import sbtbiswas.AidenOnTheGo.features.bots.AidenBotResumeController +import sbtbiswas.AidenOnTheGo.features.bots.AidenBotResumeTransport import sbtbiswas.AidenOnTheGo.features.bots.AidenDurableFailureSettlement import sbtbiswas.AidenOnTheGo.features.bots.AidenDurablePendingMutation import sbtbiswas.AidenOnTheGo.features.bots.aidenBotAvatarMutationFailureIsAmbiguous @@ -20,11 +31,19 @@ import sbtbiswas.AidenOnTheGo.features.bots.aidenBotMacAnswered import sbtbiswas.AidenOnTheGo.features.bots.aidenBotMessageFailureIsAmbiguous import sbtbiswas.AidenOnTheGo.features.bots.aidenBotResumeFailureIsAmbiguous import sbtbiswas.AidenOnTheGo.features.chat.AidenChatForkErrors +import sbtbiswas.AidenOnTheGo.features.scheduled.AidenScheduledRunIdempotencyKeys import sbtbiswas.AidenOnTheGo.features.scheduled.aidenScheduledRunFailureIsAmbiguous +import sbtbiswas.AidenOnTheGo.models.AidenBotResumeRequest +import sbtbiswas.AidenOnTheGo.models.AidenBotResumeStatus +import sbtbiswas.AidenOnTheGo.models.AidenBotSessionState +import sbtbiswas.AidenOnTheGo.models.AidenBotSessionStateView import sbtbiswas.AidenOnTheGo.models.AidenNewWorktreeRetry +import sbtbiswas.AidenOnTheGo.networking.AidenRemoteClient +import sbtbiswas.AidenOnTheGo.persistence.AidenBotWatchJournalStore import java.io.File import java.io.IOException import java.net.SocketTimeoutException +import java.time.Instant import java.util.UUID class AidenRemoteFailureClassificationTest { @@ -225,4 +244,233 @@ class AidenRemoteFailureClassificationTest { ) ) } + + @Test + fun parseErrorDistinguishesMalformed409FromDecoded409InternalErrorAndRetainsKeys() { + val malformed409Bodies = listOf( + // Real 409 idempotency_in_flight that fails duplicate-key validation + """{"error":{"code":"idempotency_in_flight","code":"idempotency_in_flight","message":"Still running","requestId":"req_dup","retryable":true}}""", + // Truncated JSON + "{\"error\":{\"code\":\"idempotency_in_flight\"", + // Missing required envelope fields + """{"error":{"code":"idempotency_in_flight"}}""", + // Plain text proxy/server error + "Conflict", + // Empty body + "" + ) + + for (raw in malformed409Bodies) { + val parsed = AidenRemoteClient.parseError(409, raw.toByteArray(Charsets.UTF_8)) + assertEquals(409, parsed.statusCode) + assertFalse("malformed body must not be marked as decoded envelope: $raw", parsed.isDecodedEnvelope) + + for (policy in AidenRemoteFailurePolicy.entries) { + assertTrue( + "malformed 409 ($raw) must remain ambiguous under $policy", + AidenRemoteFailureClassification.isAmbiguous(parsed, policy) + ) + } + assertTrue(aidenBotMessageFailureIsAmbiguous(parsed)) + assertFalse(aidenBotMacAnswered(parsed)) + assertTrue(aidenBotResumeFailureIsAmbiguous(parsed)) + assertTrue(aidenBotAvatarMutationFailureIsAmbiguous(parsed)) + assertTrue(aidenScheduledRunFailureIsAmbiguous(parsed)) + assertTrue(AidenChatForkErrors.isOutcomeUnknown(parsed)) + assertFalse("new-worktree must keep key on malformed 409 ($raw)", AidenNewWorktreeRetry.spendsKey(parsed)) + + val botKey1 = UUID.fromString("11111111-1111-4111-8111-111111111111") + val botKey2 = UUID.fromString("22222222-2222-4222-8222-222222222222") + val botKeys = AidenBotActionKeys(ArrayDeque(listOf(botKey1, botKey2))::removeFirst) + assertEquals(botKey1, botKeys.key("stop")) + botKeys.failed("stop", parsed) + assertEquals("Bot action key must be retained on malformed 409 ($raw)", botKey1, botKeys.key("stop")) + + val runKey1 = UUID.fromString("33333333-3333-4333-8333-333333333333") + val runKey2 = UUID.fromString("44444444-4444-4444-8444-444444444444") + val runKeys = AidenScheduledRunIdempotencyKeys(ArrayDeque(listOf(runKey1, runKey2))::removeFirst) + assertEquals(runKey1, runKeys.keyFor("task_1")) + runKeys.failed("task_1", parsed) + assertEquals("Scheduled run key must be retained on malformed 409 ($raw)", runKey1, runKeys.keyFor("task_1")) + } + + // Malformed non-409 envelopes also retain keys under BEFORE_EFFECT_REFUSAL*, CACHED_REJECTION_LEDGER, and fork. + val malformed400 = AidenRemoteClient.parseError(400, "not json".toByteArray(Charsets.UTF_8)) + assertFalse(malformed400.isDecodedEnvelope) + assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)) + assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT)) + assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER)) + assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT)) + assertTrue(aidenBotMessageFailureIsAmbiguous(malformed400)) + assertFalse(aidenBotMacAnswered(malformed400)) + assertTrue(aidenScheduledRunFailureIsAmbiguous(malformed400)) + assertTrue(AidenChatForkErrors.isOutcomeUnknown(malformed400)) + + // Contrast: a genuinely decoded structured 409 internal_error settles the key in cached-rejection ledger policies. + val decoded409Internal = AidenRemoteClient.parseError( + 409, + """{"error":{"code":"internal_error","message":"Settled rejection","requestId":"req_409","retryable":false}}""" + .toByteArray(Charsets.UTF_8) + ) + assertTrue(decoded409Internal.isDecodedEnvelope) + assertEquals(AidenRemoteErrorCode.INTERNAL_ERROR, decoded409Internal.body.code) + assertFalse(AidenRemoteFailureClassification.isAmbiguous(decoded409Internal, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER)) + assertFalse(AidenRemoteFailureClassification.isAmbiguous(decoded409Internal, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT)) + assertFalse(aidenBotMessageFailureIsAmbiguous(decoded409Internal)) + assertTrue(aidenBotMacAnswered(decoded409Internal)) + assertFalse(aidenScheduledRunFailureIsAmbiguous(decoded409Internal)) + assertFalse(AidenChatForkErrors.isOutcomeUnknown(decoded409Internal)) + assertTrue(AidenNewWorktreeRetry.spendsKey(decoded409Internal)) + assertTrue(AidenRemoteFailureClassification.isAmbiguous(decoded409Internal, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)) + + // Contrast: a genuinely decoded 409 idempotency_in_flight keeps the key everywhere. + val decoded409InFlight = AidenRemoteClient.parseError( + 409, + """{"error":{"code":"idempotency_in_flight","message":"Still running","requestId":"req_inflight","retryable":true}}""" + .toByteArray(Charsets.UTF_8) + ) + assertTrue(decoded409InFlight.isDecodedEnvelope) + assertEquals(AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT, decoded409InFlight.body.code) + for (policy in AidenRemoteFailurePolicy.entries) { + assertTrue(AidenRemoteFailureClassification.isAmbiguous(decoded409InFlight, policy)) + } + assertFalse(AidenNewWorktreeRetry.spendsKey(decoded409InFlight)) + } + + @Test + fun malformed409OverHttpRetainsIdempotencyKeyAcrossScheduledRunAndBotControllers() = runBlocking { + val server = MockWebServer() + server.start() + try { + val client = AidenRemoteClient( + endpoint = server.url("/api/aiden/v1").toString().trimEnd('/'), + credential = "test-credential", + customOkHttpClient = OkHttpClient.Builder().build() + ) + + // 1. Scheduled task run-now: malformed 409 retains Idempotency-Key across retry; decoded 409 internal_error clears it. + val runKey1 = UUID.fromString("11111111-1111-4111-8111-111111111111") + val runKey2 = UUID.fromString("22222222-2222-4222-8222-222222222222") + val runKey3 = UUID.fromString("33333333-3333-4333-8333-333333333333") + val scheduledKeys = AidenScheduledRunIdempotencyKeys(ArrayDeque(listOf(runKey1, runKey2, runKey3))::removeFirst) + + server.enqueue( + MockResponse() + .setResponseCode(409) + .setBody("""{"error":{"code":"idempotency_in_flight","code":"idempotency_in_flight","message":"In flight","requestId":"req_1","retryable":true}}""") + ) + server.enqueue( + MockResponse() + .setResponseCode(202) + .setBody("""{"taskId":"task_1","runId":"run_1","status":"queued","acceptedAt":"2026-11-24T05:00:00Z"}""") + ) + + val firstRunError = try { + client.runScheduledTask("task_1", "rev_1", scheduledKeys.keyFor("task_1")) + fail("Expected HTTP 409 to throw") + throw AssertionError() + } catch (error: AidenRemoteClientException.Server) { + error + } + assertFalse(firstRunError.isDecodedEnvelope) + scheduledKeys.failed("task_1", firstRunError) + assertEquals(runKey1, scheduledKeys.keyFor("task_1")) + + client.runScheduledTask("task_1", "rev_1", scheduledKeys.keyFor("task_1")) + scheduledKeys.accepted("task_1") + + val req1 = server.takeRequest() + val req2 = server.takeRequest() + assertEquals(runKey1.toString(), req1.getHeader("Idempotency-Key")) + assertEquals(runKey1.toString(), req2.getHeader("Idempotency-Key")) + + server.enqueue( + MockResponse() + .setResponseCode(409) + .setBody("""{"error":{"code":"internal_error","message":"Settled rejection","requestId":"req_settled","retryable":false}}""") + ) + val settledRunError = try { + client.runScheduledTask("task_2", "rev_1", scheduledKeys.keyFor("task_2")) + fail("Expected HTTP 409 to throw") + throw AssertionError() + } catch (error: AidenRemoteClientException.Server) { + error + } + assertTrue(settledRunError.isDecodedEnvelope) + scheduledKeys.failed("task_2", settledRunError) + assertEquals(runKey3, scheduledKeys.keyFor("task_2")) + assertNotEquals(runKey2, scheduledKeys.keyFor("task_2")) + server.takeRequest() + + // 2. Bot action keys over HTTP: truncated 409 retains the Idempotency-Key for stopBotSession. + val stopKey1 = UUID.fromString("55555555-5555-4555-8555-555555555555") + val stopKey2 = UUID.fromString("66666666-6666-4666-8666-666666666666") + val botKeys = AidenBotActionKeys(ArrayDeque(listOf(stopKey1, stopKey2))::removeFirst) + + server.enqueue( + MockResponse() + .setResponseCode(409) + .setBody("{\"error\":{\"code\":\"idempotency_in_flight\"") + ) + server.enqueue( + MockResponse() + .setResponseCode(200) + .setBody("""{"state":"idle","interrupted":false}""") + ) + + val stopError = try { + client.stopBotSession("bot-1", botKeys.key("stop")) + fail("Expected HTTP 409 to throw") + throw AssertionError() + } catch (error: AidenRemoteClientException.Server) { + error + } + assertFalse(stopError.isDecodedEnvelope) + botKeys.failed("stop", stopError) + assertEquals(stopKey1, botKeys.key("stop")) + + val stopResult = client.stopBotSession("bot-1", botKeys.key("stop")) + assertEquals(AidenBotSessionState.IDLE, stopResult.state) + val stopReq1 = server.takeRequest() + val stopReq2 = server.takeRequest() + assertEquals(stopKey1.toString(), stopReq1.getHeader("Idempotency-Key")) + assertEquals(stopKey1.toString(), stopReq2.getHeader("Idempotency-Key")) + + // 3. Bot resume controller backed by real AidenRemoteClient: malformed 409 retains pending key and replays it. + val resumeKey = UUID.fromString("77777777-7777-4777-8777-777777777777") + val journal = AidenBotWatchJournalStore(InMemoryAidenSecureStore(), "bot-routine-controls", 1088) + .journal("host", "phone", Instant.EPOCH, "bot-1|resume") { true } + val resumeTransport = object : AidenBotResumeTransport { + override suspend fun status(): AidenBotResumeStatus = AidenBotResumeStatus(false) + override suspend fun resume(key: UUID, request: AidenBotResumeRequest): AidenBotSessionStateView = + client.resumeBotSession("bot-1", key, request) + } + val resumeController = AidenBotResumeController( + transport = resumeTransport, + mayResume = { true }, + supportsPreflight = { true }, + version = { "v1" }, + journal = journal, + uuid = { resumeKey }, + now = { 1_000L } + ) + + server.enqueue(MockResponse().setResponseCode(409).setBody("Conflict")) + server.enqueue(MockResponse().setResponseCode(200).setBody("""{"state":"running","interrupted":false}""")) + + assertNull(resumeController.request()) + assertNotNull("malformed 409 must retain pending resume attempt", resumeController.state.value.pending) + val resumed = resumeController.request() + assertNotNull(resumed) + assertEquals(AidenBotSessionState.RUNNING, resumed!!.state) + assertNull(resumeController.state.value.pending) + + val resumeReq1 = server.takeRequest() + val resumeReq2 = server.takeRequest() + assertEquals(resumeKey.toString(), resumeReq1.getHeader("Idempotency-Key")) + assertEquals(resumeKey.toString(), resumeReq2.getHeader("Idempotency-Key")) + } finally { + server.shutdown() + } + } } From 9f39b9c10575d830b9551a426a81a7540eb78b11 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 11:57:25 -0500 Subject: [PATCH 3/5] android: treat 409 revision_conflict as a before-effect refusal on every route Android's before-effect allowlist now holds the same 31 codes as iOS and the mutation-failure-ambiguity fixture, so resume, open-work, peers and routine-models settle a first 409 revision_conflict (and the domain refusals) as definite. The separate WITH_REVISION_CONFLICT policy for watches and avatar is folded into the single policy. An attempt that was already unknown still stays uncertain whatever a later response says. --- android/CHANGELOG.md | 1 + .../bots/AidenBotGeneratedAvatarLifecycle.kt | 2 +- .../features/bots/AidenBotWatchController.kt | 2 +- .../AidenRemoteFailureClassification.kt | 69 +++++++------ .../bots/AidenBotOpenWorkControllerTest.kt | 14 +-- .../bots/AidenBotPeersControllerTest.kt | 7 ++ .../bots/AidenBotResumeControllerTest.kt | 16 ++- .../AidenBotRoutineModelsControllerTest.kt | 12 ++- .../bots/AidenBotSessionControllerTest.kt | 16 ++- .../AidenRemoteFailureClassificationTest.kt | 97 ++++++++++++++----- 10 files changed, 162 insertions(+), 74 deletions(-) diff --git a/android/CHANGELOG.md b/android/CHANGELOG.md index a60c3fd748..faf74857bc 100644 --- a/android/CHANGELOG.md +++ b/android/CHANGELOG.md @@ -4,6 +4,7 @@ Aiden On The Go for Android. Earlier Android changes are recorded in the pull re ## Unreleased +- **2026-11-24 — One before-effect refusal list, matching iOS.** Resume, Open work, Peers, Routine models, Watches and the generated avatar now share one list of refusals that prove a change never ran: the same 31 codes as iOS and `recognizedBeforeEffectCodes` in `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json`. A first `409 revision_conflict` on any of them clears the pending attempt instead of keeping it as uncertain, as do `already_exists` and the handle, approval, question, memory, proposal, hand-off, access-request and plan-expiry refusals. An attempt whose earlier try was already unknown still stays uncertain whatever a later response says. No Remote wire or revision change. - **2026-11-18 — Pairing with a server; Terminal theme control removed.** The pairing steps now say that on a server, `aiden serve` shows the code in its terminal, or `aiden remote pair lan` prints one, as iOS already did. The app no longer accepts the retired `appearance.terminalTheme` chat control, which no host has sent since the interactive CLI was retired on 2026-10-30. No Remote wire or revision change. - **2026-11-11 — Continue in a new chat (Remote revision 64; written as 63, re-claimed at merge on 2026-11-17).** When a host offering `chat:continue-in-new-chat` refuses a send because the chat's workspace folder is missing and says the chat can continue elsewhere, the error gains **Continue in a new chat**. A sheet lists the host's other workspaces (never the chat's own, archived ones or any folder path); picking one forks the whole chat into that workspace with the host's `continueIn` request and opens the new chat, leaving the original as it was. Failures show the host's message; a destination whose folder is missing too keeps the action so another workspace can be picked. Without the host's offer, or on older hosts, the refusal looks as before. Bot contract-test revision assertions now expect 63. diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt index b7f4b15e0f..9b518ee1cf 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt @@ -66,7 +66,7 @@ fun aidenBotAvatarMutationFailureIsAmbiguous(error: Throwable): Boolean { if (error is AidenBotGeneratedAvatarError.Unavailable) return false return AidenRemoteFailureClassification.isAmbiguous( error, - AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL ) } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt index 1f6284b84b..80296963a6 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotWatchController.kt @@ -223,7 +223,7 @@ class AidenBotWatchController(private val transport: AidenBotWatchTransport, pri val settlement = AidenDurablePendingMutation.settleFailure( error = e, previouslyUnknown = wasPending, - policy = AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + policy = AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL ) val definite = settlement == AidenDurableFailureSettlement.CLEAR_DEFINITE val permissionDenied = server?.statusCode in listOf(401, 403) diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt index 878c7ce0f1..6419e7adef 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt @@ -10,24 +10,19 @@ import kotlinx.coroutines.CancellationException */ enum class AidenRemoteFailurePolicy { /** - * Strict before-effect refusal allowlist for Bot control and custom-receipt routes - * (`resume`, `open-work`, `peers`, `routine-models`). + * Strict before-effect refusal allowlist for Bot control, custom-receipt and revision-checked + * routes (`resume`, `open-work`, `peers`, `routine-models`, `watches`, `avatar`). * - * Only structured 4xx responses (excluding `408`/`429`) whose error code is on - * [AidenRemoteFailureClassification.BEFORE_EFFECT_REFUSAL_CODES] prove the request had no - * effect. `409 idempotency_in_flight`, `409 internal_error`, unknown `409`s, `400` with + * Only structured 4xx responses (excluding `408`/`429`) with a decoded error envelope whose + * code is on [AidenRemoteFailureClassification.BEFORE_EFFECT_REFUSAL_CODES] prove the request + * had no effect. That list includes `409 revision_conflict`: the host's revision check rejects + * a stale write before anything is written, and the ledger replays that same refusal under the + * key. `409 idempotency_in_flight`, `409 internal_error`, unknown `409`s, `400` with * unrecognized codes, `5xx`, `408`, `429`, unstructured [AidenRemoteClientException.UnexpectedStatus], * transport/parse failures, and [CancellationException] are all ambiguous. */ BEFORE_EFFECT_REFUSAL, - /** - * Same strict before-effect refusal allowlist as [BEFORE_EFFECT_REFUSAL], plus - * `409 revision_conflict` for routes whose optimistic-concurrency revision check rejects - * stale writes before any effect (`watches`, `avatar`). - */ - BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT, - /** * Durable idempotency ledger routes (`executeAidenDurableOperation`) aligned with * `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json` (`messages`, Bot session @@ -55,10 +50,14 @@ enum class AidenRemoteFailurePolicy { object AidenRemoteFailureClassification { /** - * Structured error codes the host returns strictly before any Bot control or custom-receipt - * mutation effect can commit. + * Structured error codes the host returns strictly before any mutation effect can commit. + * + * This is the cross-client list: it must equal `recognizedBeforeEffectCodes` in + * `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json` and iOS's + * `AidenRemoteFailureClassification.beforeEffectCodes`. */ val BEFORE_EFFECT_REFUSAL_CODES: Set = setOf( + // Core protocol, auth, admission, and Bot resume before-effect refusals AidenRemoteErrorCode.INVALID_REQUEST, AidenRemoteErrorCode.PAYLOAD_TOO_LARGE, AidenRemoteErrorCode.AUTHENTICATION_REQUIRED, @@ -71,7 +70,26 @@ object AidenRemoteFailureClassification { AidenRemoteErrorCode.BOT_PAUSED, AidenRemoteErrorCode.IDEMPOTENCY_CONFLICT, AidenRemoteErrorCode.IDEMPOTENCY_CAPACITY, - AidenRemoteErrorCode.RATE_LIMITED + AidenRemoteErrorCode.RATE_LIMITED, + // Domain before-effect CAS, validation, and precondition refusals + AidenRemoteErrorCode.REVISION_CONFLICT, + AidenRemoteErrorCode.ALREADY_EXISTS, + AidenRemoteErrorCode.HANDLE_INVALID, + AidenRemoteErrorCode.HANDLE_EXPIRED, + AidenRemoteErrorCode.HANDLE_WRONG_DEVICE, + AidenRemoteErrorCode.HANDLE_CAPACITY, + AidenRemoteErrorCode.APPROVAL_ALREADY_RESOLVED, + AidenRemoteErrorCode.APPROVAL_RESOLVED, + AidenRemoteErrorCode.APPROVAL_EXPIRED, + AidenRemoteErrorCode.QUESTION_ALREADY_RESOLVED, + AidenRemoteErrorCode.QUESTION_EXPIRED, + AidenRemoteErrorCode.MEMORY_ENTRY_NOT_FOUND, + AidenRemoteErrorCode.MEMORY_OVER_BUDGET, + AidenRemoteErrorCode.MEMORY_BLOCKED, + AidenRemoteErrorCode.ROUTINE_PROPOSAL_NOT_FOUND, + AidenRemoteErrorCode.HANDOFF_EXPIRED, + AidenRemoteErrorCode.ACCESS_REQUEST_EXPIRED, + AidenRemoteErrorCode.PLAN_EXPIRED ) private fun isPreSendLocalError(error: Throwable): Boolean = when (error) { @@ -102,10 +120,7 @@ object AidenRemoteFailureClassification { if (error is CancellationException) return true if (isPreSendLocalError(error)) return false return when (policy) { - AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL -> - isBeforeEffectAmbiguous(error, allowRevisionConflict = false) - AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT -> - isBeforeEffectAmbiguous(error, allowRevisionConflict = true) + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL -> isBeforeEffectAmbiguous(error) AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER -> isCachedRejectionLedgerAmbiguous(error) AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT -> @@ -113,16 +128,12 @@ object AidenRemoteFailureClassification { } } - private fun isBeforeEffectAmbiguous(error: Throwable, allowRevisionConflict: Boolean): Boolean = when (error) { - is AidenRemoteClientException.Server -> { - if (!error.isDecodedEnvelope || isTransientHttpStatus(error.statusCode) || error.statusCode !in 400..499) { - true - } else { - val allowed = error.body.code in BEFORE_EFFECT_REFUSAL_CODES || - (allowRevisionConflict && error.body.code == AidenRemoteErrorCode.REVISION_CONFLICT) - !allowed - } - } + private fun isBeforeEffectAmbiguous(error: Throwable): Boolean = when (error) { + is AidenRemoteClientException.Server -> + !error.isDecodedEnvelope || + isTransientHttpStatus(error.statusCode) || + error.statusCode !in 400..499 || + error.body.code !in BEFORE_EFFECT_REFUSAL_CODES is AidenRemoteClientException.UnexpectedStatus -> true else -> true } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt index 03e9b473c1..c1350e119e 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotOpenWorkControllerTest.kt @@ -175,12 +175,14 @@ class AidenBotOpenWorkControllerTest { assertEquals(listOf(OPEN_NONCE,OPEN_NONCE),host.writes.map{it.mutationId}) } - // A first proven before-effect refusal clears pending and reports FAILED. - val host=Host();val c=controller(host);c.load();c.begin(host.view.items.single());c.edit{it.copy(title="Refused")} - host.answer={throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Denied","req_6",false))} - c.save() - assertNull(c.state.value.pending) - assertEquals(AidenOpenWorkProblem.FAILED,c.state.value.problem) + // A first proven before-effect refusal, including 409 revision_conflict, clears pending and reports FAILED. + for((status,code) in listOf(403 to AidenRemoteErrorCode.CAPABILITY_DENIED,409 to AidenRemoteErrorCode.REVISION_CONFLICT)) { + val host=Host();val c=controller(host);c.load();c.begin(host.view.items.single());c.edit{it.copy(title="Refused")} + host.answer={throw AidenRemoteClientException.Server(status,AidenRemoteErrorEnvelope.Body(code,"Refused","req_6",false))} + c.save() + assertNull("$status $code clears pending",c.state.value.pending) + assertEquals(AidenOpenWorkProblem.FAILED,c.state.value.problem) + } // If clearing a first definite refusal fails in storage, STORAGE is preserved and further writes stay blocked. var failClear=false;var saved:String?=null diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt index 99401525b9..2228a829e4 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotPeersControllerTest.kt @@ -52,6 +52,13 @@ class AidenBotPeersControllerTest { val p=Phone();val c=p.controller();c.load();c.setDraft("Draft") p.host.write={if(failure is AidenPeerError)AidenPeerMutationResult(false,code=failure,error="Publication unconfirmed") else throw failure as Exception};c.saveDescription();assertNotNull(c.state.value.pending) } + // A first 409 revision_conflict proves the description was never written. + run { + val p=Phone();val c=p.controller();c.load();c.setDraft("Draft") + p.host.write={throw AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.REVISION_CONFLICT,"Changed","req",false))} + c.saveDescription();assertNull(c.state.value.pending);assertEquals(AidenRoutineControlProblem.FAILED,c.state.value.problem) + assertNull("a cleared attempt does not come back after restart",p.controller().state.value.pending) + } val p=Phone();val c=p.controller();c.load();c.setDraft("Draft");p.host.write={AidenPeerMutationResult(false,code=AidenPeerError.CONFLICT,error="Changed",snapshot=p.host.settings.copy(revision="next"))};c.saveDescription() assertNull(c.state.value.pending);assertTrue(c.state.value.needsReview);assertEquals("Draft",c.state.value.draft);assertFalse(c.saveAllowed()) c.reviewKeepingDraft();assertEquals("next",c.state.value.baseline!!.revision);assertTrue(c.saveAllowed()) diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeControllerTest.kt index 469124ec68..82eb00c529 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotResumeControllerTest.kt @@ -109,8 +109,10 @@ class AidenBotResumeControllerTest { active=true;visit="next foreground" host.answer={throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Refused","req",false))} restored.request();assertNotNull(restored.state.value.pending) + host.answer={throw AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.REVISION_CONFLICT,"Changed","req",false))} + restored.request();assertNotNull("a later revision_conflict cannot settle an unknown attempt",restored.state.value.pending) host.answer={AidenBotSessionStateView(AidenBotSessionState.RUNNING,false)};assertNotNull(restored.request()) - assertEquals(1,host.reads);assertEquals(3,host.writes.size) + assertEquals(1,host.reads);assertEquals(4,host.writes.size) assertTrue(host.writes.all{it.first==nonce && it.second.expectedSubmissionId==source && it.second.expectedCostReceiptId==COST_RECEIPT_A}) assertNull(restored.state.value.pending);assertNull(journal(secure).read()) } @@ -156,13 +158,17 @@ class AidenBotResumeControllerTest { restored.request();assertEquals(1,host.writes.size);assertNull(restored.state.value.pending) } @Test fun firstDefinitiveDenialClearsButStorageFailureAndSecondWindowForbidTransmission()=runTest { - val host=Host();host.answer={throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Denied","req",false))} - val c=controller(host);c.request();assertNull(c.state.value.pending);assertEquals(AidenRoutineControlProblem.FAILED,c.state.value.problem) + for((status,code) in listOf(403 to AidenRemoteErrorCode.CAPABILITY_DENIED,409 to AidenRemoteErrorCode.REVISION_CONFLICT)) { + val refused=Host();refused.answer={throw AidenRemoteClientException.Server(status,AidenRemoteErrorEnvelope.Body(code,"Refused","req",false))} + val secure=InMemoryAidenSecureStore();val c=controller(refused,journal(secure));c.request() + assertNull("$status $code clears pending",c.state.value.pending);assertNull(journal(secure).read());assertEquals(AidenRoutineControlProblem.FAILED,c.state.value.problem) + } + val host=Host() val secure=InMemoryAidenSecureStore();val one=controller(host,journal(secure));val two=controller(host,journal(secure)) host.answer={throw IOException("Lost")};one.request();two.request() - assertEquals(2,host.writes.size);assertEquals(AidenRoutineControlProblem.STORAGE,two.state.value.problem) + assertEquals(1,host.writes.size);assertEquals(AidenRoutineControlProblem.STORAGE,two.state.value.problem) val failed=controller(host,object:AidenBotWatchJournal{override fun read():String?=null;override fun write(record:String?){error("disk")}}) - failed.request();assertEquals(2,host.writes.size);assertEquals(AidenRoutineControlProblem.STORAGE,failed.state.value.problem) + failed.request();assertEquals(1,host.writes.size);assertEquals(AidenRoutineControlProblem.STORAGE,failed.state.value.problem) } @Test fun failedPreflightAndReadOnlyAccessNeverSendResume()=runTest { val host=Host();val c=controller(host);host.statusAnswer={throw IOException("Offline")};assertNull(c.request());assertTrue(host.writes.isEmpty());assertNull(c.state.value.pending) diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt index 82e1cfd189..64a4ec5e48 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotRoutineModelsControllerTest.kt @@ -122,10 +122,12 @@ class AidenBotRoutineModelsControllerTest { assertEquals(listOf(MODEL_NONCE,MODEL_NONCE),host.writes.map{it.mutationId}) } - val host=Host();val c=controller(host);c.load();c.select(primary,false) - host.answer={throw AidenRemoteClientException.Server(403,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.CAPABILITY_DENIED,"Denied","req_4",false))} - c.save() - assertNull(c.state.value.pending) - assertEquals(AidenRoutineControlProblem.FAILED,c.state.value.problem) + for((status,code) in listOf(403 to AidenRemoteErrorCode.CAPABILITY_DENIED,409 to AidenRemoteErrorCode.REVISION_CONFLICT)) { + val host=Host();val c=controller(host);c.load();c.select(primary,false) + host.answer={throw AidenRemoteClientException.Server(status,AidenRemoteErrorEnvelope.Body(code,"Refused","req_4",false))} + c.save() + assertNull("$status $code clears pending",c.state.value.pending) + assertEquals(AidenRoutineControlProblem.FAILED,c.state.value.problem) + } } } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt index a9a4b4ee29..6ea276cf92 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotSessionControllerTest.kt @@ -943,7 +943,7 @@ class AidenBotSessionControllerTest { } @Test fun legacyFirstTypedUnknownOutcomeKeepsItsUuidAndReconcilesCachedStateWithoutAnotherMutation()=runTest { - for(code in listOf("idempotency_in_flight","internal_error","new_resume_recovery","revision_conflict")) { + for(code in listOf("idempotency_in_flight","internal_error","new_resume_recovery")) { val base=FakeTransport(interruptedSession);val seen=mutableListOf();var first=true val transport=object:AidenBotSessionTransport by base { override suspend fun resume(botId:String,key:UUID):AidenBotSessionStateView { @@ -959,6 +959,20 @@ class AidenBotSessionControllerTest { } } + @Test fun legacyFirstRevisionConflictIsADefiniteRefusalSoTheNextResumeMintsANewKey()=runTest { + val base=FakeTransport(interruptedSession);val seen=mutableListOf();var first=true + val transport=object:AidenBotSessionTransport by base { + override suspend fun resume(botId:String,key:UUID):AidenBotSessionStateView { + seen+=key + if(first) {first=false;throw AidenRemoteClientException.Server(409,AidenRemoteErrorEnvelope.Body(AidenRemoteErrorCode.REVISION_CONFLICT,"Changed","req",false))} + return AidenBotSessionStateView(AidenBotSessionState.RUNNING,false) + } + } + val controller=AidenBotSessionController(interruptedSession.botId,transport,backgroundScope) + controller.refetch();assertFalse(controller.resume());assertTrue(controller.state.value.isInterrupted) + controller.resume();assertEquals(2,seen.size);assertNotEquals(seen[0],seen[1]) + } + @Test fun doubleResumeSendsOneRequestAndARetryReusesItsKey() = runTest { val transport = FakeTransport(interruptedSession) diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt index bc3d4ab136..e22204c505 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt @@ -108,6 +108,7 @@ class AidenRemoteFailureClassificationTest { server(503, AidenRemoteErrorCode.INTERNAL_ERROR), server(408, AidenRemoteErrorCode.INVALID_REQUEST), server(429, AidenRemoteErrorCode.RATE_LIMITED), + server(503, AidenRemoteErrorCode.REVISION_CONFLICT), AidenRemoteClientException.UnexpectedStatus(400), AidenRemoteClientException.UnexpectedStatus(409), AidenRemoteClientException.InvalidResponse() @@ -117,28 +118,10 @@ class AidenRemoteFailureClassificationTest { "$error must stay ambiguous under BEFORE_EFFECT_REFUSAL", AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) ) - assertTrue( - "$error must stay ambiguous under BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT", - AidenRemoteFailureClassification.isAmbiguous( - error, - AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT - ) - ) + assertTrue("Resume keeps pending on $error", aidenBotResumeFailureIsAmbiguous(error)) + assertTrue("Avatar keeps pending on $error", aidenBotAvatarMutationFailureIsAmbiguous(error)) } - val revisionConflict = server(409, AidenRemoteErrorCode.REVISION_CONFLICT) - assertTrue( - "Resume does not use revision_conflict as a before-effect refusal", - AidenRemoteFailureClassification.isAmbiguous(revisionConflict, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) - ) - assertFalse( - "Watches and Avatar reject stale If-Match before effect", - AidenRemoteFailureClassification.isAmbiguous( - revisionConflict, - AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT - ) - ) - val definiteRefusals = listOf( server(400, AidenRemoteErrorCode.INVALID_REQUEST), server(401, AidenRemoteErrorCode.AUTHENTICATION_REQUIRED), @@ -147,6 +130,8 @@ class AidenRemoteFailureClassificationTest { server(409, AidenRemoteErrorCode.OPERATION_STALE), server(409, AidenRemoteErrorCode.BOT_PAUSED), server(409, AidenRemoteErrorCode.IDEMPOTENCY_CONFLICT), + // The host's revision check refuses a stale write before anything is written. + server(409, AidenRemoteErrorCode.REVISION_CONFLICT), server(413, AidenRemoteErrorCode.PAYLOAD_TOO_LARGE), server(422, AidenRemoteErrorCode.INVALID_REQUEST) ) @@ -155,11 +140,60 @@ class AidenRemoteFailureClassificationTest { "$error is a proven before-effect refusal", AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL) ) - assertFalse( - "$error is a proven before-effect refusal with revision conflict enabled", + assertFalse("Resume clears pending on $error", aidenBotResumeFailureIsAmbiguous(error)) + assertFalse("Avatar clears pending on $error", aidenBotAvatarMutationFailureIsAmbiguous(error)) + } + } + + /** + * The cross-client before-effect refusal list. It mirrors `recognizedBeforeEffectCodes` in + * `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json` and iOS's + * `AidenRemoteFailureClassification.beforeEffectCodes`; once that fixture is on this branch, + * read it here instead of this copy. + */ + private val crossClientBeforeEffectCodes = listOf( + "invalid_request", "payload_too_large", "authentication_required", "credential_revoked", + "capability_denied", "server_identity_changed", "not_found", "bot_archived", + "operation_stale", "bot_paused", "idempotency_conflict", "idempotency_capacity", + "rate_limited", "revision_conflict", "already_exists", "handle_invalid", "handle_expired", + "handle_wrong_device", "handle_capacity", "approval_already_resolved", "approval_resolved", + "approval_expired", "question_already_resolved", "question_expired", + "memory_entry_not_found", "memory_over_budget", "memory_blocked", + "routine_proposal_not_found", "handoff_expired", "access_request_expired", "plan_expired" + ) + + @Test + fun beforeEffectPolicySettlesExactlyTheCrossClientRefusalCodes() { + assertEquals(31, crossClientBeforeEffectCodes.toSet().size) + for (raw in crossClientBeforeEffectCodes) { + for (status in listOf(400, 403, 404, 409, 410, 422)) { + assertFalse( + "$status $raw is a before-effect refusal", + AidenRemoteFailureClassification.isAmbiguous( + server(status, AidenRemoteErrorCode(raw)), + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL + ) + ) + } + for (status in listOf(408, 429, 500, 503)) { + assertTrue( + "transient $status $raw leaves the outcome unknown", + AidenRemoteFailureClassification.isAmbiguous( + server(status, AidenRemoteErrorCode(raw)), + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL + ) + ) + } + } + // Every other code the protocol knows stays ambiguous, so the settled set is no wider. + val others = AidenRemoteErrorCode.V1_KNOWN.map { it.rawValue } - crossClientBeforeEffectCodes.toSet() + assertTrue(others.isNotEmpty()) + for (raw in others + "future_refusal") { + assertTrue( + "409 $raw must stay ambiguous", AidenRemoteFailureClassification.isAmbiguous( - error, - AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT + server(409, AidenRemoteErrorCode(raw)), + AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL ) ) } @@ -243,6 +277,18 @@ class AidenRemoteFailureClassificationTest { previouslyUnknown = false ) ) + + // A first 409 revision_conflict is definite, but it cannot settle an attempt whose + // earlier try was already unknown. + val revisionConflict = server(409, AidenRemoteErrorCode.REVISION_CONFLICT) + assertEquals( + AidenDurableFailureSettlement.CLEAR_DEFINITE, + AidenDurablePendingMutation.settleFailure(revisionConflict, previouslyUnknown = false) + ) + assertEquals( + AidenDurableFailureSettlement.RETAIN_UNCERTAIN, + AidenDurablePendingMutation.settleFailure(revisionConflict, previouslyUnknown = true) + ) } @Test @@ -294,11 +340,10 @@ class AidenRemoteFailureClassificationTest { assertEquals("Scheduled run key must be retained on malformed 409 ($raw)", runKey1, runKeys.keyFor("task_1")) } - // Malformed non-409 envelopes also retain keys under BEFORE_EFFECT_REFUSAL*, CACHED_REJECTION_LEDGER, and fork. + // Malformed non-409 envelopes also retain keys under BEFORE_EFFECT_REFUSAL, CACHED_REJECTION_LEDGER, and fork. val malformed400 = AidenRemoteClient.parseError(400, "not json".toByteArray(Charsets.UTF_8)) assertFalse(malformed400.isDecodedEnvelope) assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)) - assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL_WITH_REVISION_CONFLICT)) assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER)) assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT)) assertTrue(aidenBotMessageFailureIsAmbiguous(malformed400)) From 1e8a147208cb5c51bb9a3791fb35ccf2583dd36d Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 12:16:59 -0500 Subject: [PATCH 4/5] android: keep the key on 5xx/408/429 for fork, continue and new-worktree These routes use the host's cached-rejection ledger like messages and run-now, so a structured 5xx, 408 or 429 leaves the attempt ambiguous. The STRICT variant that spent the key on those statuses is folded into CACHED_REJECTION_LEDGER; new-worktree keeps its unreadable-response rule. --- android/CHANGELOG.md | 2 +- .../features/chat/AidenChatFork.kt | 9 ++-- .../AidenOnTheGo/models/AidenNewWorktree.kt | 8 ++-- .../AidenRemoteFailureClassification.kt | 44 +++++++------------ .../AidenOnTheGo/AidenNewWorktreeTest.kt | 34 +++++++++++++- .../AidenRemoteFailureClassificationTest.kt | 13 +++--- docs/aiden-remote-api-v1.md | 2 +- 7 files changed, 65 insertions(+), 47 deletions(-) diff --git a/android/CHANGELOG.md b/android/CHANGELOG.md index faf74857bc..83b2221d20 100644 --- a/android/CHANGELOG.md +++ b/android/CHANGELOG.md @@ -4,7 +4,7 @@ Aiden On The Go for Android. Earlier Android changes are recorded in the pull re ## Unreleased -- **2026-11-24 — One before-effect refusal list, matching iOS.** Resume, Open work, Peers, Routine models, Watches and the generated avatar now share one list of refusals that prove a change never ran: the same 31 codes as iOS and `recognizedBeforeEffectCodes` in `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json`. A first `409 revision_conflict` on any of them clears the pending attempt instead of keeping it as uncertain, as do `already_exists` and the handle, approval, question, memory, proposal, hand-off, access-request and plan-expiry refusals. An attempt whose earlier try was already unknown still stays uncertain whatever a later response says. No Remote wire or revision change. +- **2026-11-24 — One before-effect refusal list, matching iOS.** Resume, Open work, Peers, Routine models, Watches and the generated avatar now share one list of refusals that prove a change never ran: the same 31 codes as iOS and `recognizedBeforeEffectCodes` in `protocol/aiden-remote/v1/fixtures/mutation-failure-ambiguity.json`. A first `409 revision_conflict` on any of them clears the pending attempt instead of keeping it as uncertain, as do `already_exists` and the handle, approval, question, memory, proposal, hand-off, access-request and plan-expiry refusals. An attempt whose earlier try was already unknown still stays uncertain whatever a later response says. Fork, Continue in a new chat and New worktree now follow the same cached-rejection-ledger rule as messages and run-now: a structured `5xx`, `408` or `429` keeps the request's key for the retry instead of spending it. No Remote wire or revision change. - **2026-11-18 — Pairing with a server; Terminal theme control removed.** The pairing steps now say that on a server, `aiden serve` shows the code in its terminal, or `aiden remote pair lan` prints one, as iOS already did. The app no longer accepts the retired `appearance.terminalTheme` chat control, which no host has sent since the interactive CLI was retired on 2026-10-30. No Remote wire or revision change. - **2026-11-11 — Continue in a new chat (Remote revision 64; written as 63, re-claimed at merge on 2026-11-17).** When a host offering `chat:continue-in-new-chat` refuses a send because the chat's workspace folder is missing and says the chat can continue elsewhere, the error gains **Continue in a new chat**. A sheet lists the host's other workspaces (never the chat's own, archived ones or any folder path); picking one forks the whole chat into that workspace with the host's `continueIn` request and opens the new chat, leaving the original as it was. Failures show the host's message; a destination whose folder is missing too keeps the action so another workspace can be picked. Without the host's offer, or on older hosts, the refusal looks as before. Bot contract-test revision assertions now expect 63. diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt index 11bbceade0..da1bf4f3fa 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatFork.kt @@ -78,14 +78,15 @@ object AidenChatForkErrors { /** * Whether a failed fork may still have been created, so a retry must - * replay the same idempotency key. That holds only when no error response - * arrived (a lost connection or timeout) or the Mac is still running the - * first request. The Mac's idempotency ledger settles every other error + * replay the same idempotency key. That holds when no readable error + * response arrived (a lost connection, a timeout or an unreadable body), + * when the Mac is still running the first request, and on a `5xx`, `408` + * or `429`. The Mac's idempotency ledger settles every other error * response as a rejection, and replaying its key would only return * `internal_error`, so the next attempt needs a fresh key. */ fun isOutcomeUnknown(error: Throwable): Boolean = - AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT) + AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER) /** A summary route's 404 or 409 means the summary already changed elsewhere. */ fun isSummaryMovedOn(error: Throwable): Boolean = isNotFound(error) || isRevisionConflict(error) diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt index a00692618d..7de12c8b25 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/models/AidenNewWorktree.kt @@ -25,13 +25,13 @@ object AidenNewWorktreeRetry { /** * The Mac keeps each answer under its key for a day, refusals included, so a request it * answered needs a new key next time. One that got no answer (no connection, a timeout, - * Cancel) or that the Mac is still working on keeps its key, so the retry gets what the Mac - * did with it. An answer this phone could not read spends it too: the Mac would only replay - * the same answer under that key. + * Cancel), that the Mac is still working on, or that got a `5xx`, `408` or `429` keeps its + * key, so the retry gets what the Mac did with it. An answer this phone could not read + * spends it: the Mac would only replay the same answer under that key. */ fun spendsKey(error: Throwable): Boolean = !AidenRemoteFailureClassification.isAmbiguous( error, - AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT, + AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER, unreadableResponseAmbiguous = false ) } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt index 6419e7adef..3d44327b95 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassification.kt @@ -24,28 +24,24 @@ enum class AidenRemoteFailurePolicy { BEFORE_EFFECT_REFUSAL, /** - * Durable idempotency ledger routes (`executeAidenDurableOperation`) aligned with - * `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json` (`messages`, Bot session - * control actions, scheduled task run-now, Bot create): - * - `5xx`, `408`, `429`, and `409 idempotency_in_flight` are ambiguous (keep key). + * Durable idempotency ledger routes (`executeAidenDurableOperation` and + * `AidenIdempotencyLedger`) aligned with + * `protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json`: `messages`, Bot session + * control actions, scheduled task run-now, Bot create, chat `fork`, `continue-in-new-chat` + * and `new-worktree`. + * - Structured `5xx`, `408` and `429` responses, and `idempotency_in_flight`, are ambiguous + * (keep key). * - Other structured 4xx responses with a genuinely decoded error envelope (including * replayed settled rejections such as `409 internal_error` and `409 idempotency_conflict`) * settle the key. * - Unreadable/malformed error envelopes ([AidenRemoteClientException.Server.isDecodedEnvelope] * == `false`), unstructured [AidenRemoteClientException.UnexpectedStatus], transport/parse * failures, and [CancellationException] are ambiguous (keep key), because an unreadable HTTP - * 409 may have been `409 idempotency_in_flight`. + * 409 may have been `409 idempotency_in_flight`. A route that passes + * `unreadableResponseAmbiguous = false` to [AidenRemoteFailureClassification.isAmbiguous] + * spends the key on unreadable non-409 responses instead. */ - CACHED_REJECTION_LEDGER, - - /** - * Durable idempotency ledger routes (`fork`, `continue-in-new-chat`, `new-worktree`) where - * the host caches every structured server rejection under the key for 24 hours: - * - `409 idempotency_in_flight`, unreadable/malformed error envelopes (including any - * undecodable HTTP 409), transport failures, and [CancellationException] keep the key; - * any other genuinely decoded [AidenRemoteClientException.Server] response spends it. - */ - CACHED_REJECTION_LEDGER_STRICT + CACHED_REJECTION_LEDGER } object AidenRemoteFailureClassification { @@ -122,9 +118,7 @@ object AidenRemoteFailureClassification { return when (policy) { AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL -> isBeforeEffectAmbiguous(error) AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER -> - isCachedRejectionLedgerAmbiguous(error) - AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT -> - isCachedRejectionLedgerStrictAmbiguous(error, unreadableResponseAmbiguous) + isCachedRejectionLedgerAmbiguous(error, unreadableResponseAmbiguous) } } @@ -138,16 +132,7 @@ object AidenRemoteFailureClassification { else -> true } - private fun isCachedRejectionLedgerAmbiguous(error: Throwable): Boolean = when (error) { - is AidenRemoteClientException.Server -> - !error.isDecodedEnvelope || - isTransientHttpStatus(error.statusCode) || - (error.statusCode == 409 && error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT) - is AidenRemoteClientException.UnexpectedStatus -> true - else -> true - } - - private fun isCachedRejectionLedgerStrictAmbiguous( + private fun isCachedRejectionLedgerAmbiguous( error: Throwable, unreadableResponseAmbiguous: Boolean ): Boolean = when (error) { @@ -155,7 +140,8 @@ object AidenRemoteFailureClassification { if (!error.isDecodedEnvelope) { unreadableResponseAmbiguous || error.statusCode == 409 } else { - error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT + isTransientHttpStatus(error.statusCode) || + error.body.code == AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT } is AidenRemoteClientException.UnexpectedStatus -> unreadableResponseAmbiguous || error.statusCode == 409 diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenNewWorktreeTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenNewWorktreeTest.kt index 55cc5df20a..4291be82b0 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenNewWorktreeTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenNewWorktreeTest.kt @@ -228,7 +228,7 @@ class AidenNewWorktreeTest { fun refusal(status: Int, code: AidenRemoteErrorCode) = AidenRemoteClientException.Server(status, AidenRemoteErrorEnvelope.Body(code, "Refused.", "req_1", false)) assertTrue(AidenNewWorktreeRetry.spendsKey(refusal(409, AidenRemoteErrorCode("git_capability_denied")))) - assertTrue(AidenNewWorktreeRetry.spendsKey(refusal(500, AidenRemoteErrorCode.INTERNAL_ERROR))) + assertFalse("a server error leaves the outcome unknown", AidenNewWorktreeRetry.spendsKey(refusal(500, AidenRemoteErrorCode.INTERNAL_ERROR))) assertTrue(AidenNewWorktreeRetry.spendsKey(AidenRemoteClientException.UnexpectedStatus(502))) assertTrue("an answer the phone could not read would only replay", AidenNewWorktreeRetry.spendsKey(AidenRemoteClientException.InvalidResponse())) assertFalse("the Mac is still on it", AidenNewWorktreeRetry.spendsKey(refusal(409, AidenRemoteErrorCode.IDEMPOTENCY_IN_FLIGHT))) @@ -485,6 +485,38 @@ class AidenNewWorktreeTest { } } + @Test + fun aServerErrorKeepsTheWorktreeKeyAndOnlyTheMacsRefusalSpendsIt() { + val mac = Mac(emptyChat) + fun refusal(status: Int, code: String, id: String) = MockResponse().setResponseCode(status).setBody( + """{"error":{"code":"$code","message":"Not now.","requestId":"$id","retryable":false}}""" + ) + val answers = java.util.concurrent.ConcurrentLinkedQueue(listOf( + refusal(503, "internal_error", "worktree-1"), + refusal(409, "operation_in_progress", "worktree-2"), + refusal(409, "operation_in_progress", "worktree-3") + )) + withEmptyWorkspaceChat(mac, route = { path -> + when (path) { + "/chats/chat-new/worktree" -> answers.poll() + else -> null + } + }) { model, _ -> + for (attempt in 1..3) { + model.updateDraft("Fix the header") + model.setStartsInNewWorktree(true) + model.send() + withTimeout(5_000) { while (mac.worktreeKeys().size < attempt) delay(10) } + withTimeout(5_000) { model.isStarting.first { !it } } + assertTrue(model.chat.value!!.messages.isEmpty()) + } + val keys = mac.worktreeKeys() + assertEquals("a 503 may have made the worktree, so the retry keeps its key", keys[0], keys[1]) + assertNotEquals("the Mac answered the refusal, so the next request has a new key", keys[1], keys[2]) + assertEquals("no message was sent", List(3) { "/chats/chat-new/worktree" }, mac.posted()) + } + } + @Test fun aChatThatStoppedQualifyingKeepsItsMessageInsteadOfSendingToTheMainCheckout() { val mac = Mac(emptyChat) diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt index e22204c505..1f5bfbb133 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/protocol/AidenRemoteFailureClassificationTest.kt @@ -200,7 +200,7 @@ class AidenRemoteFailureClassificationTest { } @Test - fun cachedRejectionLedgerMatchesSharedBotOutboxFixtureAndPreservesStrictReplayContract() { + fun cachedRejectionLedgerRoutesMatchSharedBotOutboxFixture() { val relative = "protocol/aiden-remote/v1/fixtures/bot-outbox-delivery.json" val root = generateSequence(File(System.getProperty("user.dir")!!).absoluteFile) { it.parentFile } .first { File(it, relative).isFile } @@ -220,12 +220,13 @@ class AidenRemoteFailureClassificationTest { AidenRemoteFailureClassification.isAmbiguous(error, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER) ) assertEquals(name, expected, aidenScheduledRunFailureIsAmbiguous(error)) + // Fork, continue-in-new-chat and new-worktree are cached-rejection-ledger routes too: + // a structured 5xx, 408 or 429 keeps the key, like every other ledger route. + assertEquals("fork: $name", expected, AidenChatForkErrors.isOutcomeUnknown(error)) + assertEquals("new-worktree: $name", expected, !AidenNewWorktreeRetry.spendsKey(error)) } - // Strict cached-rejection endpoints spend the key on 500 internal_error as well. - val server500 = server(500, AidenRemoteErrorCode.INTERNAL_ERROR) - assertFalse(AidenChatForkErrors.isOutcomeUnknown(server500)) - assertTrue(AidenNewWorktreeRetry.spendsKey(server500)) + // Only an unreadable non-409 answer separates new-worktree: the Mac would replay it. assertTrue(AidenNewWorktreeRetry.spendsKey(AidenRemoteClientException.UnexpectedStatus(502))) assertTrue(AidenNewWorktreeRetry.spendsKey(AidenRemoteClientException.InvalidResponse())) assertFalse(AidenNewWorktreeRetry.spendsKey(SocketTimeoutException("timeout"))) @@ -345,7 +346,6 @@ class AidenRemoteFailureClassificationTest { assertFalse(malformed400.isDecodedEnvelope) assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.BEFORE_EFFECT_REFUSAL)) assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER)) - assertTrue(AidenRemoteFailureClassification.isAmbiguous(malformed400, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT)) assertTrue(aidenBotMessageFailureIsAmbiguous(malformed400)) assertFalse(aidenBotMacAnswered(malformed400)) assertTrue(aidenScheduledRunFailureIsAmbiguous(malformed400)) @@ -360,7 +360,6 @@ class AidenRemoteFailureClassificationTest { assertTrue(decoded409Internal.isDecodedEnvelope) assertEquals(AidenRemoteErrorCode.INTERNAL_ERROR, decoded409Internal.body.code) assertFalse(AidenRemoteFailureClassification.isAmbiguous(decoded409Internal, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER)) - assertFalse(AidenRemoteFailureClassification.isAmbiguous(decoded409Internal, AidenRemoteFailurePolicy.CACHED_REJECTION_LEDGER_STRICT)) assertFalse(aidenBotMessageFailureIsAmbiguous(decoded409Internal)) assertTrue(aidenBotMacAnswered(decoded409Internal)) assertFalse(aidenScheduledRunFailureIsAmbiguous(decoded409Internal)) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 4ace8ac552..cb1dc28ee8 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1148,7 +1148,7 @@ Revision 53 is provisional and is re-claimed at merge, after whatever `main` hol **Negotiation.** Phones already hear the most `/server` `features` that shipped clients accept (32), so this revision adds no feature token. The host lists `chat:new-worktree` in `serverCapabilities` while it can make worktrees. A device asks for it with `POST /device/capabilities {accepts: ["chat:new-worktree"]}` in a call of its **own**, after its other opt-ins: a host older than revision 53 refuses the unknown name with `400 invalid_request`. Pairing never issues it. The route also needs `git:write`, so the opt-in alone grants nothing. -**Route.** `POST /chats/{chatId}/worktree` (`chat:write`, `git:write`, `chat:new-worktree`) takes `If-Match` (the chat's revision), an `Idempotency-Key`, and exactly `{ text }`: the chat's first message, not blank, at most 4,000 characters. It sends nothing. The host picks the base the way a desktop draft does by default (the repository's default branch, fetched from its remote when it has one, else the branch the checkout is on), names the branch `aiden/`, makes the worktree through the same first-message path as the desktop (one worktree per chat), and moves the empty chat into the new worktree's workspace. It answers `200` with exactly `{ chat, branch }`: the chat projection, still with no messages, in its new workspace and with a new revision, and the branch name (at most 200 characters). The device then sends its turn as usual. For 24 hours the same key and `text` replay a `200` answer as it was, whatever revision the retry carries. A refusal settles the key instead: a same-key retry answers `409 internal_error` ("This chat request cannot be safely repeated."), not the first refusal's code or message. So a device mints a new key after any answer and keeps one only across a request that got no answer. An empty chat that is already in the worktree this route made for it (an earlier attempt finished after the device stopped waiting) answers `200` with that chat and its worktree's branch, whatever revision or key the request carries, and makes nothing. A chat moved into any other worktree gets the usual revision check. +**Route.** `POST /chats/{chatId}/worktree` (`chat:write`, `git:write`, `chat:new-worktree`) takes `If-Match` (the chat's revision), an `Idempotency-Key`, and exactly `{ text }`: the chat's first message, not blank, at most 4,000 characters. It sends nothing. The host picks the base the way a desktop draft does by default (the repository's default branch, fetched from its remote when it has one, else the branch the checkout is on), names the branch `aiden/`, makes the worktree through the same first-message path as the desktop (one worktree per chat), and moves the empty chat into the new worktree's workspace. It answers `200` with exactly `{ chat, branch }`: the chat projection, still with no messages, in its new workspace and with a new revision, and the branch name (at most 200 characters). The device then sends its turn as usual. For 24 hours the same key and `text` replay a `200` answer as it was, whatever revision the retry carries. A refusal settles the key instead: a same-key retry answers `409 internal_error` ("This chat request cannot be safely repeated."), not the first refusal's code or message. So a device mints a new key after a refusal, and keeps its key across a request that got no answer, `idempotency_in_flight`, or a `5xx`, `408` or `429`, any of which may have left the worktree made. An empty chat that is already in the worktree this route made for it (an earlier attempt finished after the device stopped waiting) answers `200` with that chat and its worktree's branch, whatever revision or key the request carries, and makes nothing. A chat moved into any other worktree gets the usual revision check. **Refusals.** Every refusal is a fixed sentence without a path or Git's own output: - a chat with messages: `409 operation_stale` ("This chat already has messages, so it stays in its workspace."); From db2f86fd02c09377a83bff30033688cda77e011a Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 12:16:59 -0500 Subject: [PATCH 5/5] android: reuse the avatar upload key after an uncertain failure uploadAvatar now keeps an uncertain attempt and retries the same photo and revision under the same Idempotency-Key, using the before-effect policy. A first definite refusal clears it; a later refusal of an uncertain attempt does not. Replaces a test that only exercised its own copy of the rule. --- .../bots/AidenBotGeneratedAvatarLifecycle.kt | 22 ++++- .../AidenBotGeneratedAvatarTest.kt | 97 +++++++++++++++++-- 2 files changed, 108 insertions(+), 11 deletions(-) diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt index 9b518ee1cf..7c366cbdf6 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/AidenBotGeneratedAvatarLifecycle.kt @@ -40,6 +40,7 @@ import sbtbiswas.AidenOnTheGo.ui.theme.AidenActivityDot import java.io.ByteArrayOutputStream import java.security.MessageDigest import java.util.Base64 +import java.util.UUID import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.ui.res.stringResource import sbtbiswas.AidenOnTheGo.R @@ -178,6 +179,18 @@ class AidenBotGeneratedAvatarModel( /** The last photo the Mac took, kept until a refreshed Bot that carries it is seen. */ @Volatile private var committed: CommittedAvatar? = null + private class UploadAttempt(val botId: String, val revision: String, val data: ByteArray, val key: UUID) { + fun isFor(botId: String, revision: String, data: ByteArray): Boolean = + this.botId == botId && this.revision == revision && this.data.contentEquals(data) + } + + /** + * An upload whose outcome is unknown. Sending the same photo to the same Bot revision again + * reuses its `Idempotency-Key`, so the Mac replays what it did rather than taking the photo a + * second time. A reply, or a refusal that proves nothing was written, ends it. + */ + @Volatile private var uncertainUpload: UploadAttempt? = null + /** * The If-Match for the next avatar change. A photo the Mac took whose Bot could not be re-read * still moved the avatar revision on, so a page holding the older Bot sends the committed one. @@ -237,10 +250,16 @@ class AidenBotGeneratedAvatarModel( } _phase.value = AidenBotGeneratedAvatarPhase.UPLOADING + val earlier = uncertainUpload?.takeIf { it.isFor(botId, revision, data) } + // Once an attempt is uncertain, no later refusal can prove the first try did nothing. + val retried = earlier != null + val attempt = earlier ?: UploadAttempt(botId, revision, data, UUID.randomUUID()) + uncertainUpload = attempt try { val base64Data = Base64.getEncoder().encodeToString(data) val upload = AidenBotAvatarUpload(data = base64Data) - val asset = client.putBotAvatar(botId, revision, upload) + val asset = client.putBotAvatar(botId, revision, upload, attempt.key) + if (uncertainUpload === attempt) uncertainUpload = null committed = CommittedAvatar(botId, revision, asset.assetRevision) botCache?.putAvatar(botId, asset.assetRevision, data) // A pick made during the upload owns the phase and the candidate now. @@ -263,6 +282,7 @@ class AidenBotGeneratedAvatarModel( } catch (e: CancellationException) { throw e } catch (e: Exception) { + if (!retried && !aidenBotAvatarMutationFailureIsAmbiguous(e) && uncertainUpload === attempt) uncertainUpload = null if (mine == selection) { _phase.value = AidenBotGeneratedAvatarPhase.FAILED _errorMessage.value = e.message ?: "Avatar upload failed" diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotGeneratedAvatarTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotGeneratedAvatarTest.kt index 56a71a2573..09eb79398b 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotGeneratedAvatarTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotGeneratedAvatarTest.kt @@ -147,18 +147,95 @@ class AidenBotGeneratedAvatarTest { } @Test - fun testMutationAmbiguityClassification() { - fun isAmbiguous(statusCode: Int?, isNetworkError: Boolean): Boolean { - if (isNetworkError) return true - return statusCode == 503 || statusCode == 504 + fun anUncertainUploadRetriesWithItsKeyAndADefiniteRefusalLetsTheNextOneMintANewKey() { + val directory = kotlin.io.path.createTempDirectory("avatar-retry-").toFile() + val server = MockWebServer() + val uploads = java.util.concurrent.LinkedBlockingQueue() + fun error(status: Int, code: String) = MockResponse().setResponseCode(status).setBody( + """{"error":{"code":"$code","message":"Not now","requestId":"r","retryable":false}}""") + val answers = java.util.concurrent.ConcurrentLinkedQueue(listOf( + error(503, "internal_error"), + error(409, "idempotency_in_flight"), + error(409, "revision_conflict"), + error(409, "revision_conflict") + )) + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = + if (request.method == "PUT" && request.requestUrl!!.encodedPath.endsWith("/bots/bot-1/avatar")) { + uploads.add(request) + answers.poll() ?: MockResponse().setResponseCode(500) + } else MockResponse().setResponseCode(404) } + server.start() + try { + val installations = AidenInstallationStore(directory, InMemoryAidenSecureStore()) + installations.addInstallation(AidenPairingExchange(instanceId = "instance-avatar", deviceId = "device-avatar", + endpoint = server.url("/api/aiden/v1").toString(), serverSpkiSha256 = "sha256/test", credential = "synthetic", + capabilities = listOf(AidenRemoteCapability.CHAT_READ)), null) + val coordinator = AidenRemoteCoordinator( + installationStore = installations, + storageDir = directory, + chatCache = AidenChatCache(directory), + scope = CoroutineScope(Dispatchers.Unconfined + Job().apply { cancel() }) + ) + coordinator.refreshClient() + val model = AidenBotGeneratedAvatarModel(coordinator, normalize = { it }) + runBlocking { + assertTrue(model.setCandidate(byteArrayOf(1))) + repeat(4) { + model.uploadAvatar("bot-1", "rev-1") { fail("every upload is refused") } + assertEquals(AidenBotGeneratedAvatarPhase.FAILED, model.phase.value) + } + } + val keys = List(4) { uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)!!.getHeader("Idempotency-Key") } + assertEquals("a 503 leaves the upload uncertain, so the retry keeps its key", keys[0], keys[1]) + assertEquals("the Mac is still on it, so the key is kept", keys[1], keys[2]) + assertEquals("a revision_conflict cannot settle an upload that was already uncertain", keys[2], keys[3]) + } finally { + server.shutdown() + directory.deleteRecursively() + } + } - assertTrue(isAmbiguous(null, isNetworkError = true)) - assertTrue(isAmbiguous(503, isNetworkError = false)) - assertTrue(isAmbiguous(504, isNetworkError = false)) - assertFalse(isAmbiguous(400, isNetworkError = false)) - assertFalse(isAmbiguous(409, isNetworkError = false)) - assertFalse(isAmbiguous(422, isNetworkError = false)) + @Test + fun aFirstRevisionConflictIsDefiniteSoTheNextUploadMintsANewKey() { + val directory = kotlin.io.path.createTempDirectory("avatar-refused-").toFile() + val server = MockWebServer() + val uploads = java.util.concurrent.LinkedBlockingQueue() + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = + if (request.method == "PUT" && request.requestUrl!!.encodedPath.endsWith("/bots/bot-1/avatar")) { + uploads.add(request) + MockResponse().setResponseCode(409).setBody( + """{"error":{"code":"revision_conflict","message":"Changed","requestId":"r","retryable":false}}""") + } else MockResponse().setResponseCode(404) + } + server.start() + try { + val installations = AidenInstallationStore(directory, InMemoryAidenSecureStore()) + installations.addInstallation(AidenPairingExchange(instanceId = "instance-avatar", deviceId = "device-avatar", + endpoint = server.url("/api/aiden/v1").toString(), serverSpkiSha256 = "sha256/test", credential = "synthetic", + capabilities = listOf(AidenRemoteCapability.CHAT_READ)), null) + val coordinator = AidenRemoteCoordinator( + installationStore = installations, + storageDir = directory, + chatCache = AidenChatCache(directory), + scope = CoroutineScope(Dispatchers.Unconfined + Job().apply { cancel() }) + ) + coordinator.refreshClient() + val model = AidenBotGeneratedAvatarModel(coordinator, normalize = { it }) + runBlocking { + assertTrue(model.setCandidate(byteArrayOf(1))) + model.uploadAvatar("bot-1", "rev-1") { fail("refused") } + model.uploadAvatar("bot-1", "rev-1") { fail("refused") } + } + val first = uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)!!.getHeader("Idempotency-Key") + val second = uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)!!.getHeader("Idempotency-Key") + assertNotEquals("nothing was written, so the next upload is a new request", first, second) + } finally { + server.shutdown() + directory.deleteRecursively() + } } @Test