Modern Apps git

← Modern-Apps.git

logviewer: stream logcat output instead of holding it twice

Commit
688ed60d225b1672064feae320d785d9bdc85993
Author
Vayun Mathur <[email protected]>
When
2026-11-07 20:01 UTC (29 days ago)
Parents
9d7d024
Symptom: loading a full device log (tens of megabytes, tens of
thousands of lines) peaked at roughly twice the necessary heap:
executeCommand materialised the entire dump with toList(), then
read() copied it line by line into a second ArrayList. Both copies
were live for the whole copy. This also contradicted the stated
design in LogcatReader/LogDocument ("parsed as it streams in, so
the raw dump is never held whole alongside its lines").

Root cause: the injectable executor seam returned List<String>,
forcing the production ProcessBuilder path to collect stdout
before read() could touch a line.

Fix: the seam now returns Sequence<String>. Production yields
lines from the process stream inside useLines, then checks the
exit code (previous commit) once the stream is exhausted. read()
is unchanged apart from consuming the sequence once, stripping
the UTC offset as each line arrives. Test fakes return sequences.

Regression: new LogcatReaderTest case feeds a constrainOnce()
lazy sequence and asserts read() pulls it exactly once and in
order; LogcatReaderTest + LogcatActivityTest green.

Diff

logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.ktindex 841d832d8d..df6c6bd975 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt@@ -40,8 +40,13 @@ internal object LogcatReader {         val filterRegex: String,     ) -    /** Runs [command] and returns its stdout lines. Injectable for tests; production execs `logcat`. */-    internal var executeCommand: (List<String>) -> List<String> = { command ->+    /**+     * Runs [command] and streams its stdout lines. Injectable for tests; production execs+     * `logcat`. A [Sequence] rather than a [List] so [read] parses lines as they arrive:+     * materialising the whole dump first would hold every line twice (the raw list plus+     * the stripped copy) for a log that is already tens of megabytes.+     */+    internal var executeCommand: (List<String>) -> Sequence<String> = { command ->         val process = ProcessBuilder(command).start()         // Drain stderr concurrently: an undrained pipe fills at ~64 KiB and then blocks the         // writer, which would wedge the stdout read below forever. The text itself is useless@@ -49,15 +54,18 @@ internal object LogcatReader {         Thread {             runCatching { process.errorStream.use { it.readBytes() } }         }.apply { isDaemon = true }.start()-        val lines = process.inputStream.bufferedReader(Charsets.UTF_8).useLines { it.toList() }-        val returnCode = process.waitFor()-        Log.debug(TAG, "logcat return code: $returnCode")-        // A failed logcat (bad --regex, unknown buffer, ...) writes nothing to stdout and-        // exits non-zero. Returning those zero lines would show an empty log that looks-        // like "no entries matched", so fail the load instead and let read() map it to-        // Unavailable like any other exec failure.-        if (returnCode != 0) throw IOException("logcat exited with code $returnCode")-        lines+        sequence {+            process.inputStream.bufferedReader(Charsets.UTF_8).useLines { lines ->+                yieldAll(lines)+            }+            val returnCode = process.waitFor()+            Log.debug(TAG, "logcat return code: $returnCode")+            // A failed logcat (bad --regex, unknown buffer, ...) writes nothing to stdout and+            // exits non-zero. Surfacing those zero lines would show an empty log that looks+            // like "no entries matched", so fail the load instead and let read() map it to+            // Unavailable like any other exec failure.+            if (returnCode != 0) throw IOException("logcat exited with code $returnCode")+        }     }      /**
logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.ktindex 08c09adeca..3547b900b0 100644--- a/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/intents/LogcatActivityTest.kt@@ -41,7 +41,7 @@ class LogcatActivityTest {         fun installFakeLogcat() {             // Echo the level selector back as a line so reloads are observable on screen.             LogcatReader.executeCommand = { command ->-                listOf("log line for ${command.last()}", "second log line")+                listOf("log line for ${command.last()}", "second log line").asSequence()             }         } 
logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.ktindex 29862839aa..7423b13045 100644--- a/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/platform/LogcatReaderTest.kt@@ -43,7 +43,7 @@ class LogcatReaderTest {         var captured: List<String>? = null         LogcatReader.executeCommand = { command ->             captured = command-            listOf("first +0000 line", "second +0000 and +0000 again", "", "")+            listOf("first +0000 line", "second +0000 and +0000 again", "", "").asSequence()         }         val doc = loaded(             LogcatReader.read(@@ -71,7 +71,7 @@ class LogcatReaderTest {      @Test     fun `default buffers and verbose level leave the plain system title`() {-        LogcatReader.executeCommand = { emptyList() }+        LogcatReader.executeCommand = { emptySequence() }         val doc = loaded(             LogcatReader.read(                 context,@@ -89,7 +89,7 @@ class LogcatReaderTest {         var captured: List<String>? = null         LogcatReader.executeCommand = { command ->             captured = command-            listOf("app line")+            listOf("app line").asSequence()         }         val pkg = context.packageName         val doc = loaded(@@ -108,7 +108,7 @@ class LogcatReaderTest {     @Test     fun `unknown target package is silently unavailable and never execs`() {         var called = false-        LogcatReader.executeCommand = { called = true; emptyList() }+        LogcatReader.executeCommand = { called = true; emptySequence() }         val result = LogcatReader.read(             context,             LogcatReader.Request(@@ -159,7 +159,7 @@ class LogcatReaderTest {             (refused as LogLoadResult.Unavailable).messageRes,         ) -        LogcatReader.executeCommand = { listOf("own app line") }+        LogcatReader.executeCommand = { listOf("own app line").asSequence() }         val own = loaded(             LogcatReader.read(                 context,@@ -187,6 +187,27 @@ class LogcatReaderTest {         assertNull((result as LogLoadResult.Unavailable).messageRes)     } +    @Test+    fun `read consumes a lazy one-shot sequence`() {+        // The production executor streams process output; it cannot hand back a+        // re-readable list. read() must pull the sequence exactly once, as it goes.+        var pulled = 0+        LogcatReader.executeCommand = {+            sequence {+                pulled++; yield("streamed +0000 one")+                pulled++; yield("streamed two")+            }.constrainOnce()+        }+        val doc = loaded(+            LogcatReader.read(+                context,+                LogcatReader.Request(null, LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, ""),+            )+        )+        assertEquals(listOf("streamed one", "streamed two"), doc.bodyLines)+        assertEquals(2, pulled)+    }+     @Test     fun `request is a data holder`() {         val request = LogcatReader.Request("pkg", listOf("main"), LogLevel.Info, "x")