Skip to content

Commit 71445ce

Browse files
committed
fix(android): close remaining ack-ownership and persistence-failure gaps in the outbox
Flushed sends acked under a divergent run id now transfer local run ownership like the direct path, so live runs cannot time out and surface spurious errors for delivered turns. A session pin that cannot persist stops the dispatch while the row is still safely queued. Reconcile and timeout parking only report changes their writes actually persisted, failing closed on storage errors.
1 parent f20bd93 commit 71445ce

2 files changed

Lines changed: 155 additions & 10 deletions

File tree

‎apps/android/app/src/main/java/ai/openclaw/app/chat/ChatController.kt‎

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1977,10 +1977,17 @@ class ChatController internal constructor(
19771977
}
19781978
val sightings = (unconfirmedSightings[row.id] ?: 0) + 1
19791979
if (sightings >= 2) {
1980-
runCatching { outbox.updateStatus(row.id, ChatOutboxStatus.Failed, row.retryCount, OUTBOX_DELIVERY_UNCONFIRMED_ERROR) }
1981-
unconfirmedSightings.remove(row.id)
1982-
acknowledgedRunIdByRowId.remove(row.id)
1983-
changed = true
1980+
val persisted = updateOutboxStatusOrNull(outbox, row, ChatOutboxStatus.Failed, OUTBOX_DELIVERY_UNCONFIRMED_ERROR)
1981+
if (persisted == null) {
1982+
// The park write failed; reporting a change anyway would spin confirm/park passes
1983+
// against unavailable storage while the row's session stays blocked.
1984+
rearmOutboxRecovery()
1985+
_healthOk.value = false
1986+
} else {
1987+
unconfirmedSightings.remove(row.id)
1988+
acknowledgedRunIdByRowId.remove(row.id)
1989+
changed = true
1990+
}
19841991
} else {
19851992
unconfirmedSightings[row.id] = sightings
19861993
}
@@ -2092,7 +2099,7 @@ class ChatController internal constructor(
20922099
OutboxSendOutcome.Stop
20932100
} else {
20942101
// A zero update means a concurrent delete raced the ack; history still owns proof.
2095-
if (persisted > 0) adoptFlushedSend(item, attachments)
2102+
if (persisted > 0) adoptFlushedSend(item, attachments, result.runId)
20962103
OutboxSendOutcome.Sent
20972104
}
20982105
}
@@ -2162,10 +2169,11 @@ class ChatController internal constructor(
21622169
private fun adoptFlushedSend(
21632170
item: ChatOutboxItem,
21642171
attachments: List<OutgoingAttachment>,
2172+
ackRunId: String,
21652173
) {
21662174
if (normalizeRequestedSessionKey(item.sessionKey) != _sessionKey.value) return
21672175
val runId = item.id
2168-
if (locallyOwnedRun(runId)) return
2176+
if (locallyOwnedRun(runId) || locallyOwnedRun(ackRunId)) return
21692177
val optimistic = optimisticUserMessage(runId = runId, text = item.text, attachments = attachments)
21702178
optimisticMessagesByRunId[runId] = optimistic
21712179
unresolvedRepliesByRunId[runId] = optimistic
@@ -2175,6 +2183,9 @@ class ChatController internal constructor(
21752183
pendingRuns.add(runId)
21762184
_pendingRunCount.value = pendingRuns.size
21772185
}
2186+
// Chat events for this turn arrive under the acknowledged run id; mirroring the direct
2187+
// path's ownership transfer keeps the live run from looking foreign and timing out.
2188+
if (ackRunId != runId) transferRunOwnership(runId, ackRunId, optimistic)
21782189
}
21792190

21802191
private suspend fun attemptOutboxSend(
@@ -2188,8 +2199,18 @@ class ChatController internal constructor(
21882199
if (queuedSessionKey != item.sessionKey) {
21892200
// A row captured under the pre-hello "main" alias resolves exactly once, against the
21902201
// canonical main session active at first dispatch. Pinning it before the request means
2191-
// a later default-agent change can never redirect this input on a retry.
2192-
runCatching { outbox.pinSessionKey(item.id, queuedSessionKey) }
2202+
// a later default-agent change can never redirect this input on a retry, so a pin
2203+
// that cannot be made durable must stop the dispatch while the row is still safe.
2204+
val pinned =
2205+
try {
2206+
outbox.pinSessionKey(item.id, queuedSessionKey)
2207+
true
2208+
} catch (err: CancellationException) {
2209+
throw err
2210+
} catch (_: Throwable) {
2211+
false
2212+
}
2213+
if (!pinned) return OutboxSendResult.NotDispatched("could not pin the delivery session")
21932214
}
21942215
// Android only knows the active session's selected model. Unknown queued sessions fail
21952216
// open, preserving the thinking level captured when they were enqueued.
@@ -2512,8 +2533,13 @@ class ChatController internal constructor(
25122533
it.status == ChatOutboxStatus.Accepted &&
25132534
(it.id == runId || acknowledgedRunIdByRowId[it.id] == runId)
25142535
} ?: return
2515-
runCatching { outbox.updateStatus(row.id, ChatOutboxStatus.Failed, row.retryCount, OUTBOX_DELIVERY_UNCONFIRMED_ERROR) }
2516-
acknowledgedRunIdByRowId.remove(row.id)
2536+
val persisted = updateOutboxStatusOrNull(outbox, row, ChatOutboxStatus.Failed, OUTBOX_DELIVERY_UNCONFIRMED_ERROR)
2537+
if (persisted == null) {
2538+
rearmOutboxRecovery()
2539+
_healthOk.value = false
2540+
} else {
2541+
acknowledgedRunIdByRowId.remove(row.id)
2542+
}
25172543
publishOutbox()
25182544
}
25192545

‎apps/android/app/src/test/java/ai/openclaw/app/chat/ChatControllerOutboxTest.kt‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import kotlinx.serialization.json.JsonObject
2020
import kotlinx.serialization.json.JsonPrimitive
2121
import org.junit.Assert.assertEquals
2222
import org.junit.Assert.assertFalse
23+
import org.junit.Assert.assertNull
2324
import org.junit.Assert.assertTrue
2425
import org.junit.Test
2526
import java.util.UUID
@@ -54,6 +55,7 @@ class ChatControllerOutboxTest {
5455
var acceptedStatusUpdateFailure: Throwable? = null
5556
var queuedStatusUpdateFailure: Throwable? = null
5657
var sendingStatusUpdateFailure: Throwable? = null
58+
var pinSessionKeyFailure: Throwable? = null
5759
var claimGate: CompletableDeferred<Unit>? = null
5860
var deleteFailure: Throwable? = null
5961
var deleteOnFailedStatus = false
@@ -159,6 +161,7 @@ class ChatControllerOutboxTest {
159161
id: String,
160162
sessionKey: String,
161163
) {
164+
pinSessionKeyFailure?.let { throw it }
162165
val current = rows[id] ?: return
163166
rows[id] = current.copy(sessionKey = sessionKey)
164167
}
@@ -1922,6 +1925,122 @@ class ChatControllerOutboxTest {
19221925
assertTrue(outbox.rows.values.none { it.status == ChatOutboxStatus.Failed })
19231926
}
19241927

1928+
@Test
1929+
fun flushedSendAckedUnderDifferentRunIdResolvesWithTheLiveRun() =
1930+
runTest {
1931+
val gateway = FakeGateway()
1932+
val outbox = FakeCommandOutbox()
1933+
val chat = controller(this, gateway, outbox)
1934+
gateway.sendResponse = { _ -> """{"runId":"gw-run-9","status":"started"}""" }
1935+
gateway.echoDeliveredSendsInHistory = false
1936+
chat.load("main")
1937+
advanceUntilIdle()
1938+
1939+
// Captured offline, delivered by the reconnect flush under a divergent acked run id.
1940+
chat.sendMessageAwaitAcceptance(message = "queued turn", thinkingLevel = "off", attachments = emptyList())
1941+
gateway.online = true
1942+
chat.handleGatewayEvent("health", null)
1943+
advanceTimeBy(5_000)
1944+
assertEquals(listOf("queued turn"), gateway.sentMessages)
1945+
assertEquals(
1946+
ChatOutboxStatus.Accepted,
1947+
outbox.rows.values
1948+
.single()
1949+
.status,
1950+
)
1951+
1952+
// The run completes under the acknowledged id and its turn becomes visible in
1953+
// canonical history. The adopted send must resolve with the live run: without the
1954+
// ownership transfer the row-id pending run times out and surfaces a spurious error
1955+
// for a turn that was delivered.
1956+
gateway.echoDeliveredSendsInHistory = true
1957+
chat.handleGatewayEvent("chat", chatTerminalPayload("main", "gw-run-9", seq = 1, state = "final", assistantText = "done"))
1958+
advanceTimeBy(130_000)
1959+
assertEquals(0, chat.pendingRunCount.value)
1960+
assertTrue(outbox.rows.isEmpty())
1961+
assertNull(chat.errorText.value)
1962+
}
1963+
1964+
@Test
1965+
fun failedSessionPinKeepsTheRowQueuedInsteadOfDispatching() =
1966+
runTest {
1967+
val gateway = FakeGateway()
1968+
val outbox = FakeCommandOutbox()
1969+
val chat = controller(this, gateway, outbox)
1970+
outbox.seed(
1971+
ChatOutboxItem(
1972+
id = "alias-row",
1973+
sessionKey = "main",
1974+
text = "captured pre-hello",
1975+
thinkingLevel = "off",
1976+
createdAtMs = System.currentTimeMillis(),
1977+
status = ChatOutboxStatus.Queued,
1978+
retryCount = 0,
1979+
lastError = null,
1980+
),
1981+
)
1982+
chat.load("main")
1983+
chat.applyMainSessionKey("agent:work:main")
1984+
advanceUntilIdle()
1985+
1986+
// The durable pin is the only record of the alias resolution; if it cannot persist,
1987+
// dispatching anyway would let a retry after a default change target another session.
1988+
outbox.pinSessionKeyFailure = IllegalStateException("storage unavailable")
1989+
gateway.online = true
1990+
chat.handleGatewayEvent("health", null)
1991+
advanceUntilIdle()
1992+
assertTrue(gateway.sentMessages.isEmpty())
1993+
assertEquals(ChatOutboxStatus.Queued, outbox.rows.getValue("alias-row").status)
1994+
assertFalse(chat.healthOk.value)
1995+
1996+
// Storage recovers; the next health transition pins and delivers exactly once.
1997+
outbox.pinSessionKeyFailure = null
1998+
chat.handleGatewayEvent("health", null)
1999+
advanceUntilIdle()
2000+
assertEquals(listOf("agent:work:main"), gateway.sentSessionKeys)
2001+
assertTrue(outbox.rows.values.none { it.sessionKey == "main" })
2002+
}
2003+
2004+
@Test
2005+
fun reconcileParkWriteFailureFailsClosedThenParksAfterRecovery() =
2006+
runTest {
2007+
val gateway = FakeGateway()
2008+
val outbox = FakeCommandOutbox()
2009+
val chat = controller(this, gateway, outbox)
2010+
gateway.echoDeliveredSendsInHistory = false
2011+
outbox.seed(
2012+
ChatOutboxItem(
2013+
id = "orphan-row",
2014+
sessionKey = "main",
2015+
text = "ambiguous send",
2016+
thinkingLevel = "off",
2017+
createdAtMs = System.currentTimeMillis(),
2018+
status = ChatOutboxStatus.Accepted,
2019+
retryCount = 0,
2020+
lastError = null,
2021+
),
2022+
)
2023+
chat.load("main")
2024+
advanceUntilIdle()
2025+
2026+
// Two sightings without proof want to park the row, but the write fails: health drops
2027+
// instead of the reconciler claiming a change it never persisted.
2028+
outbox.failedStatusUpdateFailure = IllegalStateException("storage unavailable")
2029+
gateway.online = true
2030+
chat.handleGatewayEvent("health", null)
2031+
advanceUntilIdle()
2032+
assertEquals(ChatOutboxStatus.Accepted, outbox.rows.getValue("orphan-row").status)
2033+
assertFalse(chat.healthOk.value)
2034+
2035+
// Storage recovers; the next pass parks the orphan for manual review.
2036+
outbox.failedStatusUpdateFailure = null
2037+
chat.handleGatewayEvent("health", null)
2038+
advanceUntilIdle()
2039+
val parked = outbox.rows.getValue("orphan-row")
2040+
assertEquals(ChatOutboxStatus.Failed, parked.status)
2041+
assertEquals(OUTBOX_DELIVERY_UNCONFIRMED_ERROR, parked.lastError)
2042+
}
2043+
19252044
@Test
19262045
fun staleGatedParkFailureFailsClosedInsteadOfSpinning() =
19272046
runTest {

0 commit comments

Comments
 (0)