Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .memory/mobile-turn-receipt-ownership.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Android turn receipt ownership follow-up

Separate worktree /Users/sambitbiswas/.codex/worktrees/mobile-turn-receipt-ownership/aiden-agent, branch feature/mobile-turn-receipt-ownership, based on green PR225 head152577eeb0e4e7350d2f57cdf69d125cb5aa6d22. Coordinator explicitly requested keeping225 stable and publishing the next cohesive slice separately. Original217/225 worktrees untouched.

Executed baseline: actual sender POST is held while another production detail owner accepts a settled transcript. Releasing the successful receipt on225 overwrites the settled assistant with only the accepted user message. /tmp/aiden-turn-receipt-baseline.log and /tmp/aiden-turn-receipt-baseline.patch capture the failure. This is an executed current-parent negative, not a new original-main execution.

Current implementation reserves before POST, atomically admits the receipt under independent removal/purge authority, merges the accepted message by ID and canonical timestamp without replacing winner fields, and maintains separate per-chat receipt/stream ownership so an older receipt cannot replace a newer marker. Fresh detail merge authority retains the original summary ticket to avoid stale title/list projection. In-memory stream ownership survives disk-write failure; accepted202 does not restore a retryable draft merely because persistence fails. Retained original installation/device may retain the receipt for later navigation, while consumer publication requires the original active client identity. No mutation replay.

Actual two-owner regression covers a newer transcript with/without the accepted receipt, newer second POST stream ownership, purge, remove plus fresh readmission, chat disk failure and stream disk failure.185Android JVM tests/lint/instrumentation compilation pass (/tmp/aiden-turn-receipt-android.log). Both independent Sol medium reviews in progress. No iOS/server contract changes. iOS rename/list/Bot response ownership and physical acceptance remain assigned; device locked, no test launch.

Review follow-up: unpair and active-client changes reconcile the optimistic chat and clear queued state; same-ID pairing replacement is fenced using captured creation time before cache admission. Added held unpair/switch/re-pair modes. Seeded an older durable stream marker, failed its replacement before IO, and verified the memory winner survives while reopened disk cannot resume the old stream. Deleting the old marker is best effort if storage itself cannot accept deletion. Full185 JVM tests (0failures/errors/skips), lint and instrumentation compilation pass in /tmp/aiden-turn-review-android.log; focused regression /tmp/aiden-turn-review-fixed.log. Both independent GPT-5.6 Sol medium re-reviews clear the actual final source/tests. No physical execution claimed.

## Inverse completion order correction

Integration Sol identified and owner reproduced on published85f278fe: POST reserves its request ticket, a later GET reserves another ticket and holds a settled response, POST receipt completes first and mints a fresh detail write ticket, then GET is rejected and loses settled assistant/title. Actual two-ViewModel held-HTTP failure: /tmp/aiden-turn-inverse-baseline.log; exact regression patch /tmp/aiden-turn-inverse-baseline.patch. This is an executed227-parent negative.

Receipt admission now merges under original request authority and preserves max(original request, prior admitted snapshot) high-water. Persistence is a private monitor-held operation, not a new response-time request. Stream ownership remains its separate original POST receipt high-water. Receipt activity projection likewise retains existing/request summary authority, so it cannot invalidate a later GET title. Both completion orders are tested, including reopened detail/title, accepted stream marker and one POST/no retryable draft. Existing deletion, newer POST, client replacement and disk failure modes remain covered. Validation/re-review pending for this correction.

Second independent review added inverse_missing: the already-reserved GET may lack the accepted user receipt, even when its other fields are authoritative. Executed negative /tmp/aiden-turn-inverse-missing-baseline.log, focused fixed /tmp/aiden-turn-inverse-missing-fixed.log. Cache retains a receipt overlay only through the latest request ticket observed when its202 is accepted; this observes the clock without reserving authority. Already-in-flight admitted snapshots merge missing receipt IDs while preserving their own title/revision/other messages. The first snapshot requested after acceptance retires the overlay and establishes a high-water that also rejects older held reads. Remove/purge clear overlays. Added fresh retirement/remove/purge and late-old-read controls. Final186 JVM tests, lintDebug and instrumentation compilation pass /tmp/aiden-turn-inverse-final-android.log. Final independent re-reviews completed after the multi-receipt correction below.

Final multi-receipt review found POST1-first/POST2-second could use POST2's newer but pre-receipt candidate and drop receipt1. Actual two-VM held-both-POST negative: /tmp/aiden-turn-ordered-posts-baseline.log. Receipt admission now folds all pending accepted messages, independently of GET cutoff retirement. Added both POST completion orders and asserts exactly two POSTs, both message IDs once, and stream2 ownership. Final checks /tmp/aiden-turn-ordered-final-android.log; no mutation replay or server/iOS contract change.

Final acceptance for this correction:186 JVM tests,0 failures/errors/skips, lintDebug and instrumentation compilation pass. Both independent GPT-5.6 Sol medium final reviews clear after inspecting both POST orders and both GET orders. Hosted CI required on the new commit; physical acceptance remains unexecuted.
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,9 @@ class AidenChatViewModel(
_streamState.value = AidenStreamState.QUEUED

val idempotencyKey = turnAttempts.key(request)
val requestToken = chatCache.reserveChatWrite()
val pairingCreatedAt = coordinator.installationStore.installations.value
.firstOrNull { it.instanceId == instanceId && it.deviceId == deviceId }?.createdAt

viewModelScope.launch {
try {
Expand All @@ -778,26 +781,37 @@ class AidenChatViewModel(
lastSequence = 0
)

val cleanMessages = updatedChat.messages.filter { it.id != optimisticId }.toMutableList()
if (cleanMessages.none { it.id == response.message.id }) {
cleanMessages.add(response.message)
turnAttempts.reset()
val retainedInstallation = coordinator.installationStore.installations.value.any {
it.instanceId == instanceId && it.deviceId == deviceId && it.createdAt == pairingCreatedAt
}
val acceptedChat = updatedChat.copy(messages = cleanMessages)
_chat.value = acceptedChat
if (instanceId.isNotEmpty()) {
chatCache.saveChat(acceptedChat, instanceId)
chatCache.saveActiveStream(stream, instanceId, chatId)
if (!retainedInstallation) {
_chat.value = chatCache.admittedChat(instanceId, chatId)
_streamState.value = null
return@launch
}
turnAttempts.reset()
val candidate = updatedChat.copy(messages = updatedChat.messages.filter { it.id != optimisticId })
val accepted = chatCache.acceptTurnReceipt(candidate, response.message, stream, instanceId, requestToken)
if (activeClient() !== client) {
_chat.value = chatCache.admittedChat(instanceId, chatId)
_streamState.value = null
return@launch
}
if (accepted == null || !chatCache.isChatWriteRetained(instanceId, chatId, requestToken)) {
_chat.value = chatCache.admittedChat(instanceId, chatId)
_streamState.value = null
return@launch
}
_chat.value = accepted.chat

_liveText.value = ""
_reasoning.value = ""
_tools.value = emptyList()
_activityTimeline.value = null
_pendingApproval.value = null
_streamState.value = AidenStreamState.QUEUED
_streamState.value = if (accepted.stream == null) null else AidenStreamState.QUEUED

startStreaming(stream)
accepted.stream?.let { startStreaming(it) }
} catch (e: Exception) {
if (e !is CancellationException) {
val fallbackMessages = _chat.value?.messages?.filter { it.id != optimisticId } ?: emptyList()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import sbtbiswas.AidenOnTheGo.models.AidenAttachmentImageValidation
import sbtbiswas.AidenOnTheGo.models.AidenChat
import sbtbiswas.AidenOnTheGo.models.AidenChatMessage
import sbtbiswas.AidenOnTheGo.models.AidenChatRole
import sbtbiswas.AidenOnTheGo.models.AidenChatSummary
import sbtbiswas.AidenOnTheGo.models.AidenChatSummaryActivity
import sbtbiswas.AidenOnTheGo.models.AidenMessageAttachment
Expand All @@ -29,7 +31,8 @@ class AidenChatCache(
private val storageDir: File? = null,
root: File? = null,
legacyRoots: List<File>? = null,
private val maximumSummaryCacheBytes: Int = 64 * 1024 * 1024
private val maximumSummaryCacheBytes: Int = 64 * 1024 * 1024,
private val beforeActiveStreamWrite: (() -> Unit)? = null
) {
@Serializable
data class ActiveStream(
Expand Down Expand Up @@ -89,6 +92,11 @@ class AidenChatCache(
val legacyRoots: List<File>

private val writeClock = AtomicLong()
private val chatRemovalTokens = mutableMapOf<String, MutableMap<String, Long>>()
private data class ReceiptMessage(val message: AidenChatMessage, val throughWriteToken: Long)
private val receiptMessages = mutableMapOf<String, MutableMap<String, MutableList<ReceiptMessage>>>()
private val receiptTokens = mutableMapOf<String, MutableMap<String, Long>>()
private val receiptStreams = mutableMapOf<String, MutableMap<String, ActiveStream>>()
private val chatWriteTokens = mutableMapOf<String, MutableMap<String, Long>>()
private val admittedChats = mutableMapOf<String, MutableMap<String, AidenChat>>()
private val summaryWriteTokens = mutableMapOf<String, Long>()
Expand Down Expand Up @@ -332,12 +340,14 @@ class AidenChatCache(
fun updateSummaryActivity(
instanceId: String,
chatId: String,
activity: AidenChatSummaryActivity
activity: AidenChatSummaryActivity,
writeToken: Long? = null
) {
val current = summariesForInstance(instanceId)
val existing = current.firstOrNull { it.id == chatId } ?: return
if (existing.activity == activity) return
saveSummaries(current.map { if (it.id == chatId) it.copy(activity = activity) else it }, instanceId)
saveSummaries(current.map { if (it.id == chatId) it.copy(activity = activity) else it }, instanceId,
writeToken = writeToken ?: reserveChatWrite())
}

@Synchronized
Expand All @@ -358,15 +368,27 @@ class AidenChatCache(
}

@Synchronized
fun saveChat(chat: AidenChat, instanceId: String, writeToken: Long = reserveChatWrite()): Boolean {
fun saveChat(chat: AidenChat, instanceId: String, writeToken: Long = reserveChatWrite(), summaryWriteToken: Long = writeToken): Boolean {
if (writeToken <= (purgeWriteTokens[instanceId] ?: 0L) ||
writeToken <= (chatWriteTokens[instanceId]?.get(chat.id) ?: 0L)) return false
chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[chat.id] = writeToken
val ownsSummary = writeToken >= (summaryWriteTokens[instanceId] ?: 0L)
val pending = receiptMessages[instanceId]?.get(chat.id)
// Only snapshots already in flight when the receipt was accepted need
// its overlay. A later-requested snapshot can retire it, and its admitted
// high-water also prevents older in-flight snapshots from returning.
pending?.removeAll { writeToken > it.throughWriteToken }
val accepted = pending.orEmpty().fold(chat) { snapshot, receipt -> mergeReceipt(snapshot, receipt.message) }
persistAdmittedChat(accepted, instanceId, summaryWriteToken)
return true
}

// Caller holds the cache monitor and has already established request authority.
private fun persistAdmittedChat(chat: AidenChat, instanceId: String, summaryWriteToken: Long) {
val ownsSummary = summaryWriteToken >= (summaryWriteTokens[instanceId] ?: 0L)
admittedChats.getOrPut(instanceId) { mutableMapOf() }[chat.id] = chat
val visibleSummaries = summariesForInstance(instanceId).associateBy { it.id }.toMutableMap()
if (ownsSummary) {
summaryWriteTokens[instanceId] = writeToken
summaryWriteTokens[instanceId] = summaryWriteToken
if (chat.isBotChat) visibleSummaries.remove(chat.id)
else visibleSummaries[chat.id] = AidenChatSummary.fromChat(chat, visibleSummaries[chat.id]?.activity ?: AidenChatSummaryActivity.IDLE)
publishSummaries(instanceId, visibleSummaries.values.toList())
Expand All @@ -376,27 +398,77 @@ class AidenChatCache(
val map = _chats.value.toMutableMap()
map[chat.id] = chat
_chats.value = map
if (ownsSummary) saveSummaries(visibleSummaries.values.toList(), instanceId, writeToken = writeToken)
return true
if (ownsSummary) saveSummaries(visibleSummaries.values.toList(), instanceId, writeToken = summaryWriteToken)
}

private fun mergeReceipt(chat: AidenChat, message: AidenChatMessage): AidenChat {
if (chat.messages.any { it.id == message.id }) return chat
val messages = chat.messages.toMutableList()
val position = messages.indexOfFirst {
it.createdAt.isAfter(message.createdAt) ||
(it.createdAt == message.createdAt && it.role == AidenChatRole.ASSISTANT)
}.let { if (it < 0) messages.size else it }
messages.add(position, message)
return chat.copy(messages = messages)
}

data class AcceptedTurn(val chat: AidenChat, val stream: ActiveStream?)

@Synchronized
fun isChatWriteRetained(instanceId: String, chatId: String, token: Long): Boolean =
token > (purgeWriteTokens[instanceId] ?: 0L) && token > (chatRemovalTokens[instanceId]?.get(chatId) ?: 0L)

@Synchronized
fun acceptTurnReceipt(candidate: AidenChat, message: AidenChatMessage, stream: ActiveStream, instanceId: String, requestToken: Long): AcceptedTurn? {
if (!isChatWriteRetained(instanceId, candidate.id, requestToken)) return null
val winner = if ((chatWriteTokens[instanceId]?.get(candidate.id) ?: 0L) > requestToken) {
admittedChat(instanceId, candidate.id) ?: return null
} else candidate
val pending = receiptMessages.getOrPut(instanceId) { mutableMapOf() }
.getOrPut(candidate.id) { mutableListOf() }
if (pending.none { it.message.id == message.id }) pending.add(ReceiptMessage(message, writeClock.get()))
val accepted = pending.fold(winner) { snapshot, receipt -> mergeReceipt(snapshot, receipt.message) }
// Merge the accepted mutation without minting response-time authority.
// A later-started GET must remain eligible in either completion order.
// A prior admitted winner keeps its own authority and metadata.
chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[candidate.id] =
maxOf(requestToken, chatWriteTokens[instanceId]?.get(candidate.id) ?: 0L)
runCatching { persistAdmittedChat(accepted, instanceId, requestToken) }
if (requestToken > (receiptTokens[instanceId]?.get(candidate.id) ?: 0L)) {
receiptTokens.getOrPut(instanceId) { mutableMapOf() }[candidate.id] = requestToken
receiptStreams.getOrPut(instanceId) { mutableMapOf() }[candidate.id] = stream
runCatching {
saveActiveStream(stream, instanceId, candidate.id,
summaryWriteToken = maxOf(requestToken, summaryWriteTokens[instanceId] ?: 0L))
}.onFailure {
// Never leave an older receipt resumable after a failed replacement.
// Keep the accepted in-memory marker even when storage is unavailable.
runCatching { fileURL("streams", instanceId, candidate.id).delete() }
}
}
return AcceptedTurn(accepted, loadActiveStream(instanceId, candidate.id))
}

@Synchronized
fun loadActiveStream(instanceId: String, chatId: String): ActiveStream? {
receiptStreams[instanceId]?.get(chatId)?.let { return it }
val file = fileURL("streams", instanceId, chatId)
val envelope = loadEnvelope<StreamEnvelope>(file) ?: return null
if (envelope.instanceId != instanceId || envelope.chatId != chatId) return null
return envelope.stream
}

@Synchronized
fun saveActiveStream(stream: ActiveStream, instanceId: String, chatId: String) {
fun saveActiveStream(stream: ActiveStream, instanceId: String, chatId: String, summaryWriteToken: Long? = null) {
beforeActiveStreamWrite?.invoke()
val envelope = StreamEnvelope(instanceId = instanceId, chatId = chatId, stream = stream)
saveEnvelope(envelope, fileURL("streams", instanceId, chatId))
updateSummaryActivity(instanceId, chatId, AidenChatSummaryActivity.ACTIVE)
updateSummaryActivity(instanceId, chatId, AidenChatSummaryActivity.ACTIVE, summaryWriteToken)
}

@Synchronized
fun removeActiveStream(instanceId: String, chatId: String) {
receiptStreams[instanceId]?.remove(chatId)
val file = fileURL("streams", instanceId, chatId)
if (file.exists()) file.delete()
updateSummaryActivity(instanceId, chatId, AidenChatSummaryActivity.IDLE)
Expand All @@ -412,8 +484,11 @@ class AidenChatCache(

@Synchronized
fun removeChat(instanceId: String, chatId: String) {
chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[chatId] = reserveSummaryMutation(instanceId)
val removalToken = reserveSummaryMutation(instanceId)
chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[chatId] = removalToken
chatRemovalTokens.getOrPut(instanceId) { mutableMapOf() }[chatId] = removalToken
admittedChats[instanceId]?.remove(chatId)
receiptMessages[instanceId]?.remove(chatId)
val chatFile = fileURL("chats", instanceId, chatId)
if (chatFile.exists()) chatFile.delete()
removeActiveStream(instanceId, chatId)
Expand All @@ -430,6 +505,9 @@ class AidenChatCache(
purgeWriteTokens[instanceId] = reserveChatWrite()
chatWriteTokens.remove(instanceId)
admittedChats.remove(instanceId)
receiptStreams.remove(instanceId)
receiptTokens.remove(instanceId)
receiptMessages.remove(instanceId)
purgeNamespace(root, instanceId)
for (legacy in legacyRoots) {
if (legacy.canonicalPath != root.canonicalPath) {
Expand Down
Loading
Loading