Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

fix(qemu): boot-marker detection, QMP error handling, concurrent start

ExTv9cd86281f386
diff --git a/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt b/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt
index 4c0457b..cfa1dd2 100644
--- a/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt
+++ b/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt
@@ -9,9 +9,10 @@ import kotlinx.coroutines.flow.MutableStateFlow
/**
* Engine-agnostic boot-progress detector. Both engines feed it raw guest
* console bytes; it sets [bootStage] flow markers it observes and flips
- * [state] to Running when "Ready!" appears. Scans only the last 1024 chars
- * of an accumulating buffer to survive multi-byte split reads on fast
- * devices (see the history of detectBootStage in PodroidQemu pre-refactor).
+ * [state] to Running when "Ready!" appears. Each feed scans the newly-appended
+ * region plus a short overlap carried from the previous feed, so a marker that
+ * straddles a read boundary — or sits early in a single oversized chunk — is
+ * still caught (see the history of detectBootStage in PodroidQemu pre-refactor).
* One-shot: stops scanning after the first "Ready!" to keep [onReady] idempotent.
*/
class BootStageDetector(
@@ -20,8 +21,18 @@ class BootStageDetector(
private val onReady: () -> Unit,
) {
private val buf = StringBuilder()
- private val maxScan = 1024
private val maxKeep = 4096
+
+ /**
+ * Overlap carried across feeds so a marker split between two reads is still
+ * matched. (len(longest marker) - 1) chars of the previous feed are
+ * re-scanned alongside the new bytes — enough to reconstruct any marker
+ * that begins in the prior feed and ends in this one.
+ */
+ private val overlap = MARKERS.maxOf { it.first.length } - 1
+
+ /** Length of [buf] before the current feed appended — start of "new" text. */
+ private var scannedLen = 0
private var ready = false
/**
@@ -33,6 +44,7 @@ class BootStageDetector(
fun reset() {
ready = false
buf.clear()
+ scannedLen = 0
}
fun feed(bytes: ByteArray, len: Int) {
@@ -40,8 +52,18 @@ class BootStageDetector(
// Latin-1 decode is byte-safe (1 byte → 1 char) and the ASCII subset
// matches UTF-8 exactly, so our pure-ASCII markers still match.
buf.append(String(bytes, 0, len, Charsets.ISO_8859_1))
- if (buf.length > maxKeep) buf.delete(0, buf.length - maxKeep)
- val tail = if (buf.length > maxScan) buf.substring(buf.length - maxScan) else buf.toString()
+ if (buf.length > maxKeep) {
+ val dropped = buf.length - maxKeep
+ buf.delete(0, dropped)
+ scannedLen = (scannedLen - dropped).coerceAtLeast(0)
+ }
+ // Scan the new region plus an overlap into the previously-scanned text,
+ // so a marker spanning the boundary is reconstructed. Scanning the
+ // whole appended chunk (not a fixed 1024 tail) means a marker buried
+ // early in one oversized read is no longer missed.
+ val from = (scannedLen - overlap).coerceAtLeast(0)
+ val tail = buf.substring(from)
+ scannedLen = buf.length
when {
tail.contains("Ready!") -> { ready = true; bootStage.value = "Ready"; state.value = VmState.Running; onReady() }
tail.contains("Almost ready") -> bootStage.value = "Almost ready..."
@@ -53,4 +75,23 @@ class BootStageDetector(
tail.contains("Booting kernel") -> bootStage.value = "Booting kernel..."
}
}
+
+ private companion object {
+ /**
+ * The exact substrings the `when` above scans for. Used ONLY to size
+ * the cross-feed [overlap]; the `when` remains the authoritative
+ * matcher. Keep this list in sync with the `when` search strings —
+ * the longest one drives how much prior text is re-scanned.
+ */
+ val MARKERS = listOf(
+ "Ready!" to "Ready",
+ "Almost ready" to "Almost ready...",
+ "Starting SSH" to "Starting SSH...",
+ "Configuring containers" to "Configuring containers...",
+ "Network found" to "Network found",
+ "Loading kernel modules" to "Loading kernel modules...",
+ "Mounting storage" to "Mounting storage...",
+ "Booting kernel" to "Booting kernel...",
+ )
+ }
}
diff --git a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
index c2338ac..83bd9d7 100644
--- a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
@@ -38,6 +38,8 @@ import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
@@ -83,6 +85,16 @@ class QemuEngine @Inject constructor(
@Volatile
private var bootSocket: LocalSocket? = null
+ /**
+ * Last QEMU process exit code (null until it exits) + a bounded tail of
+ * QEMU's own stderr. Surfaced in the diagnostic export so a crash leaves a
+ * forensic trail. Written from start()/the stderr drain, read from the
+ * diagnostic thread — the deque is guarded by its own monitor.
+ */
+ @Volatile
+ private var lastExitCode: Int? = null
+ private val stderrTail = ArrayDeque<String>()
+
private val qmpSocketPath: String get() = "${context.filesDir.absolutePath}/qmp.sock"
override val qmpClient: QmpClient? by lazy { QmpClient(qmpSocketPath) }
@@ -115,6 +127,15 @@ class QemuEngine @Inject constructor(
/** Set once cleanup() has run for the current VM lifetime; reset by start(). */
private val cleanedUp = AtomicBoolean(true)
+ /**
+ * Serializes the start() re-entrancy guard with the Starting state write so
+ * two near-simultaneous ACTION_STARTs can't both pass the check and launch a
+ * second QEMU (orphaning the first child + leaking its executor). Held only
+ * across the guard + state flip — never across proc.waitFor() — so it can't
+ * deadlock with cleanup()/stop().
+ */
+ private val startMutex = Mutex()
+
/**
* Proxy TerminalSessionClient — delegates to whatever real client is set.
* Lets us create the bridge session at boot-complete time (before the
@@ -231,9 +252,17 @@ class QemuEngine @Inject constructor(
}
override suspend fun start(portForwards: List<PortForwardRule>, config: VmConfig) {
- if (_state.value is VmState.Starting || _state.value is VmState.Running) {
- Log.w(TAG, "start() called while VM is ${_state.value}, ignoring")
- return
+ // Atomically check the re-entrancy guard AND claim Starting before any
+ // I/O, so two concurrent ACTION_STARTs can't both pass the guard and
+ // launch a second QEMU. Held only across the guard + state flip.
+ startMutex.withLock {
+ if (_state.value is VmState.Starting || _state.value is VmState.Running) {
+ Log.w(TAG, "start() called while VM is ${_state.value}, ignoring")
+ return
+ }
+ cleanedUp.set(false)
+ bootStartTime = System.currentTimeMillis()
+ _state.value = VmState.Starting
}
val qemuExe = qemuExecutable() ?: run {
@@ -243,10 +272,10 @@ class QemuEngine @Inject constructor(
ensureStorageImage(config.storageSizeGb)
- cleanedUp.set(false)
- bootStartTime = System.currentTimeMillis()
- _state.value = VmState.Starting
- consoleBuilder.clear()
+ // consoleBuilder is also appended from the monitor coroutine; guard
+ // every access with the same lock cleanup() uses (the @Synchronized
+ // object monitor) so a concurrent append can't race this clear().
+ synchronized(this) { consoleBuilder.clear() }
_consoleText.value = ""
_bootStage.value = "Starting QEMU..."
// Re-arm the one-shot detector so a Stop → Start cycle's second boot
@@ -293,7 +322,9 @@ class QemuEngine @Inject constructor(
while (isActive) {
val n = proc.errorStream.read(buf)
if (n < 0) break
- Log.d("PodroidVM-err", String(buf, 0, n).trimEnd().take(300))
+ val chunk = String(buf, 0, n).trimEnd()
+ Log.d("PodroidVM-err", chunk.take(300))
+ recordStderr(chunk)
}
} catch (e: Exception) {
Log.d(TAG, "Stderr drain ended: ${e.message}")
@@ -308,6 +339,7 @@ class QemuEngine @Inject constructor(
while (System.currentTimeMillis() - startMs < SOCKET_READY_TIMEOUT_MS) {
if (!proc.isAlive) {
val exitCode = proc.exitValue()
+ lastExitCode = exitCode
Log.e(TAG, "QEMU died during startup, exit code: $exitCode")
_state.value = VmState.Error("QEMU exited with code $exitCode")
cleanup()
@@ -321,30 +353,48 @@ class QemuEngine @Inject constructor(
delay(200)
}
if (!socketsReady) {
+ // Don't destroyForcibly()+throw here: that kills QEMU from this
+ // IO thread and skips the dedicated-thread waitFor() reap. Set
+ // the error, signal a graceful stop, and fall through to the
+ // same waitFor() teardown the happy path uses (it reaps on the
+ // podroid-qemu thread). The guard below preserves this message.
Log.e(TAG, "Socket timeout — QEMU sockets not ready after ${SOCKET_READY_TIMEOUT_MS}ms")
- proc.destroyForcibly()
- throw RuntimeException("QEMU failed to create sockets within ${SOCKET_READY_TIMEOUT_MS / 1000}s")
- }
-
- // State stays Starting — boot monitor will set Running when "Ready!" is detected
- scope.launch {
- delay(60_000)
- if (_state.value is VmState.Starting) {
- Log.w(TAG, "Boot timeout fallback → forcing Running state")
- _bootStage.value = "Ready"
- persistBootDuration()
- _state.value = VmState.Running
- autoStartBridge()
+ _state.value =
+ VmState.Error("QEMU failed to create sockets within ${SOCKET_READY_TIMEOUT_MS / 1000}s")
+ proc.destroy()
+ } else {
+ // State stays Starting — boot monitor will set Running when "Ready!" is detected
+ scope.launch {
+ delay(60_000)
+ // Only promote a still-Starting, still-alive VM. Without the
+ // isAlive/cleanedUp check a VM that died (or stopped) in the
+ // window after delay() resumes could be flipped to a phantom
+ // Running and have the bridge re-armed after exit.
+ if (_state.value is VmState.Starting &&
+ process?.isAlive == true && !cleanedUp.get()) {
+ Log.w(TAG, "Boot timeout fallback → forcing Running state")
+ _bootStage.value = "Ready"
+ persistBootDuration()
+ _state.value = VmState.Running
+ autoStartBridge()
+ }
}
}
// Block until QEMU exits, ON THE SAME dedicated thread that fork'd
// it, so PR_SET_PDEATHSIG never fires while QEMU is healthy.
val exitCode = withContext(dispatcher) { proc.waitFor() }
+ lastExitCode = exitCode
Log.d(TAG, "QEMU exited: $exitCode")
+ val priorError = _state.value as? VmState.Error
cleanup()
- _state.value = if (exitCode == 0) VmState.Stopped
- else VmState.Error(formatExitError(exitCode, config.storageAccessEnabled))
+ // If the socket-timeout branch already set a specific Error, keep it
+ // rather than overwriting with the generic signal-exit message.
+ _state.value = when {
+ priorError != null -> priorError
+ exitCode == 0 -> VmState.Stopped
+ else -> VmState.Error(formatExitError(exitCode, config.storageAccessEnabled))
+ }
} catch (e: Exception) {
Log.e(TAG, "Failed to start QEMU", e)
_state.value = VmState.Error(e.message ?: "Unknown error")
@@ -426,11 +476,15 @@ class QemuEngine @Inject constructor(
byteBuf.compact()
charBuf.flip()
if (charBuf.hasRemaining()) {
- consoleBuilder.append(charBuf)
- if (consoleBuilder.length > maxConsoleSize) {
- consoleBuilder.delete(0, consoleBuilder.length - maxConsoleSize)
+ // Guard consoleBuilder with the same lock cleanup()/start()
+ // use, so a concurrent clear() can't corrupt the append/trim.
+ synchronized(this) {
+ consoleBuilder.append(charBuf)
+ if (consoleBuilder.length > maxConsoleSize) {
+ consoleBuilder.delete(0, consoleBuilder.length - maxConsoleSize)
+ }
+ _consoleText.value = consoleBuilder.toString()
}
- _consoleText.value = consoleBuilder.toString()
}
charBuf.clear()
@@ -652,6 +706,29 @@ class QemuEngine @Inject constructor(
return if (exe.exists()) exe else null
}
+ override fun diagnosticsReport(): String = buildString {
+ appendLine("last process exit code: ${lastExitCode?.toString() ?: "(still running / not yet exited)"}")
+ val tail = synchronized(stderrTail) { stderrTail.toList() }
+ if (tail.isEmpty()) {
+ appendLine("qemu stderr: (none captured)")
+ } else {
+ appendLine("qemu stderr (last ${tail.size} line(s)):")
+ tail.forEach { appendLine(" $it") }
+ }
+ }
+
+ /** Keep the most recent [STDERR_TAIL_LINES] non-blank stderr lines. */
+ private fun recordStderr(chunk: String) {
+ if (chunk.isBlank()) return
+ synchronized(stderrTail) {
+ for (line in chunk.lineSequence()) {
+ if (line.isBlank()) continue
+ stderrTail.addLast(line)
+ while (stderrTail.size > STDERR_TAIL_LINES) stderrTail.removeFirst()
+ }
+ }
+ }
+
/**
* Decode a QEMU process exit code into a user-facing error string. Process
* exit codes ≥128 are POSIX-encoded signals (128 + signum). On some devices
@@ -685,6 +762,7 @@ class QemuEngine @Inject constructor(
companion object {
private const val TAG = "QemuEngine"
+ private const val STDERR_TAIL_LINES = 40
/** Shared deadline for both start()'s socket-readiness loop and monitorBootSerial's wait. */
private const val SOCKET_READY_TIMEOUT_MS = 10_000L
diff --git a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
index dcfc7cb..8177a5c 100644
--- a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
@@ -22,6 +22,66 @@ class QmpClient(private val socketPath: String) {
companion object {
private const val TAG = "QmpClient"
private const val SOCKET_TIMEOUT_MS = 5000
+
+ /** Verdict for one QMP reply line. */
+ sealed class QmpVerdict {
+ /** Terminal reply: the command succeeded. */
+ object Success : QmpVerdict()
+ /** Terminal reply: the command failed (carries a human-readable reason). */
+ data class Failure(val reason: String) : QmpVerdict()
+ /** Async event line — not the reply to our command; keep reading. */
+ object SkipEvent : QmpVerdict()
+ }
+
+ /**
+ * Pure classification of an already-decomposed QMP reply. No org.json /
+ * I/O dependency, so it is directly unit-testable.
+ *
+ * - top-level `"error"` → Failure (QMP-level rejection)
+ * - `"event"` key → SkipEvent (async event, keep reading)
+ * - `"return"` string carrying a → Failure: human-monitor-command never
+ * hostfwd error sets a QMP-level error, so a busy
+ * port / bad spec arrives as return text
+ * - anything else → Success
+ *
+ * @param hasError whether the reply object has a top-level "error" key
+ * @param hasEvent whether the reply object has an "event" key
+ * @param returnValue the value of the "return" key, if present (the String
+ * body matters for human-monitor-command failures)
+ */
+ fun classifyQmpFields(hasError: Boolean, hasEvent: Boolean, returnValue: Any?): QmpVerdict {
+ if (hasError) return QmpVerdict.Failure("QMP error")
+ // Async events (SHUTDOWN, RESET, ...) can interleave with replies.
+ if (hasEvent) return QmpVerdict.SkipEvent
+ if (returnValue is String && isHostfwdError(returnValue)) {
+ return QmpVerdict.Failure("QMP human-monitor error: ${returnValue.trim()}")
+ }
+ return QmpVerdict.Success
+ }
+
+ /**
+ * Classify one parsed QMP reply object. Thin org.json adapter over
+ * [classifyQmpFields]; returns null for async-event lines so the read
+ * loop knows to keep reading for the real reply.
+ */
+ fun classifyQmpResponse(json: JSONObject): Result<JSONObject>? =
+ when (val v = classifyQmpFields(json.has("error"), json.has("event"), json.opt("return"))) {
+ is QmpVerdict.Success -> Result.success(json)
+ is QmpVerdict.Failure -> Result.failure(RuntimeException(v.reason))
+ is QmpVerdict.SkipEvent -> null
+ }
+
+ /**
+ * human-monitor-command (hostfwd_add/remove) reports failures as plain
+ * text in the `"return"` field. Match the QEMU SLIRP/hostfwd error
+ * prefixes ("could not set up host forwarding rule", "Could not ...").
+ */
+ private fun isHostfwdError(returnText: String): Boolean {
+ val t = returnText.trim()
+ if (t.isEmpty()) return false
+ return t.contains("could not set up", ignoreCase = true) ||
+ t.startsWith("Could not")
+ }
}
suspend fun execute(command: String, arguments: JSONObject? = null): Result<JSONObject> =
@@ -54,10 +114,19 @@ class QmpClient(private val socketPath: String) {
writer.write(cmd.toString() + "\n")
writer.flush()
- val response = reader.readLine()
- Log.d(TAG, "Command response: $response")
-
- Result.success(JSONObject(response ?: "{}"))
+ // Read until a terminal reply (return/error). QMP can emit
+ // async {"event":...} lines at any time — classifyQmpResponse
+ // returns null for those so we skip them. A null line = EOF.
+ var result: Result<JSONObject>? = null
+ while (result == null) {
+ val response = reader.readLine()
+ ?: return@withContext Result.failure(
+ RuntimeException("QMP connection closed before a reply to $command")
+ )
+ Log.d(TAG, "Command response: $response")
+ result = classifyQmpResponse(JSONObject(response))
+ }
+ result
}
} catch (e: Exception) {
Log.e(TAG, "QMP command failed: $command", e)
diff --git a/app/src/test/java/com/excp/podroid/engine/BootStageDetectorTest.kt b/app/src/test/java/com/excp/podroid/engine/BootStageDetectorTest.kt
new file mode 100644
index 0000000..60c8d15
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/BootStageDetectorTest.kt
@@ -0,0 +1,100 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.engine
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * BootStageDetector is shared by BOTH the QEMU and AVF backends, so every
+ * marker must keep firing for a normal boot stream. These tests pin:
+ * (a) a marker inside a single oversized (>1024-char) chunk is still seen,
+ * (b) a marker split across two feeds is still seen,
+ * (c) a normal small-chunk boot sequence still advances every stage in order
+ * and flips state to Running on "Ready!".
+ */
+class BootStageDetectorTest {
+
+ private fun newDetector(): Triple<BootStageDetector, MutableStateFlow<String>, MutableStateFlow<VmState>> {
+ val stage = MutableStateFlow("")
+ val state = MutableStateFlow<VmState>(VmState.Idle)
+ val detector = BootStageDetector(stage, state) { /* onReady */ }
+ return Triple(detector, stage, state)
+ }
+
+ private fun BootStageDetector.feed(s: String) {
+ val bytes = s.toByteArray(Charsets.ISO_8859_1)
+ feed(bytes, bytes.size)
+ }
+
+ @Test
+ fun `marker inside a single oversized chunk is detected`() {
+ val (detector, stage, _) = newDetector()
+ // One feed larger than the old 1024 scan window, with the marker buried
+ // well before the last 1024 chars so a fixed-tail scan would miss it.
+ val chunk = "x".repeat(1500) + "Almost ready..." + "y".repeat(1500)
+ detector.feed(chunk)
+ assertEquals("Almost ready...", stage.value)
+ }
+
+ @Test
+ fun `Ready split across two feeds still fires Running`() {
+ val (detector, stage, state) = newDetector()
+ detector.feed("boot output ...Rea")
+ // First feed: no full marker yet.
+ assertTrue(state.value is VmState.Idle)
+ detector.feed("dy! more output")
+ assertEquals("Ready", stage.value)
+ assertTrue(state.value is VmState.Running)
+ }
+
+ @Test
+ fun `normal small-chunk boot sequence advances every stage in order`() {
+ val (detector, stage, state) = newDetector()
+
+ detector.feed("Booting kernel...\n")
+ assertEquals("Booting kernel...", stage.value)
+
+ detector.feed("Mounting storage...\n")
+ assertEquals("Mounting storage...", stage.value)
+
+ detector.feed("Loading kernel modules...\n")
+ assertEquals("Loading kernel modules...", stage.value)
+
+ detector.feed("Network found\n")
+ assertEquals("Network found", stage.value)
+
+ detector.feed("Configuring containers...\n")
+ assertEquals("Configuring containers...", stage.value)
+
+ detector.feed("Starting SSH...\n")
+ assertEquals("Starting SSH...", stage.value)
+
+ detector.feed("Almost ready...\n")
+ assertEquals("Almost ready...", stage.value)
+
+ assertTrue(state.value is VmState.Idle)
+ detector.feed("Ready!\n")
+ assertEquals("Ready", stage.value)
+ assertTrue(state.value is VmState.Running)
+ }
+
+ @Test
+ fun `reset re-arms the one-shot so a second boot fires Running again`() {
+ val (detector, stage, state) = newDetector()
+ detector.feed("Ready!\n")
+ assertTrue(state.value is VmState.Running)
+
+ detector.reset()
+ state.value = VmState.Starting
+ // A fresh boot stream after reset must be detected again.
+ detector.feed("Booting kernel...\n")
+ assertEquals("Booting kernel...", stage.value)
+ detector.feed("Ready!\n")
+ assertTrue(state.value is VmState.Running)
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt b/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt
new file mode 100644
index 0000000..8788da1
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt
@@ -0,0 +1,80 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ */
+package com.excp.podroid.engine
+
+import com.excp.podroid.engine.QmpClient.Companion.QmpVerdict
+import com.excp.podroid.engine.QmpClient.Companion.classifyQmpFields
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Pins QMP response classification. Port-forward commands run via
+ * `human-monitor-command`, whose failures arrive as a {"return":"<error text>"}
+ * envelope (no QMP-level error, no exception), so a naive
+ * Result.success(JSONObject(line)) reports a failed forward as applied.
+ *
+ * Tests target the pure [classifyQmpFields] (no org.json) so they run as plain
+ * JVM unit tests; the thin classifyQmpResponse(JSONObject) adapter just maps its
+ * verdict onto Result/null.
+ */
+class QmpClientTest {
+
+ @Test
+ fun `top-level error envelope is a failure`() {
+ // {"error":{"class":"GenericError","desc":"bad command"}}
+ val verdict = classifyQmpFields(hasError = true, hasEvent = false, returnValue = null)
+ assertTrue(verdict is QmpVerdict.Failure)
+ }
+
+ @Test
+ fun `successful return object is a success`() {
+ // {"return":{}}
+ val verdict = classifyQmpFields(hasError = false, hasEvent = false, returnValue = emptyMap<String, Any>())
+ assertEquals(QmpVerdict.Success, verdict)
+ }
+
+ @Test
+ fun `async event line is skipped, not treated as a response`() {
+ // {"event":"SHUTDOWN",...} — keep reading for the real reply.
+ val verdict = classifyQmpFields(hasError = false, hasEvent = true, returnValue = null)
+ assertEquals(QmpVerdict.SkipEvent, verdict)
+ }
+
+ @Test
+ fun `human-monitor return carrying a hostfwd error is a failure`() {
+ // hostfwd_add on a busy port: {"return":"could not set up host forwarding rule ..."}
+ val verdict = classifyQmpFields(
+ hasError = false,
+ hasEvent = false,
+ returnValue = "could not set up host forwarding rule 'tcp::8080-:80'\r\n",
+ )
+ assertTrue(verdict is QmpVerdict.Failure)
+ }
+
+ @Test
+ fun `human-monitor return with capitalized Could not is a failure`() {
+ val verdict = classifyQmpFields(
+ hasError = false,
+ hasEvent = false,
+ returnValue = "Could not set up host forwarding rule",
+ )
+ assertTrue(verdict is QmpVerdict.Failure)
+ }
+
+ @Test
+ fun `human-monitor empty return string is a success`() {
+ // A successful hostfwd_add returns an empty string.
+ val verdict = classifyQmpFields(hasError = false, hasEvent = false, returnValue = "")
+ assertEquals(QmpVerdict.Success, verdict)
+ }
+
+ @Test
+ fun `event takes precedence is not consulted when error present`() {
+ // Defensive: an error envelope is terminal even if an event key co-occurs.
+ val verdict = classifyQmpFields(hasError = true, hasEvent = true, returnValue = null)
+ assertTrue(verdict is QmpVerdict.Failure)
+ }
+}