health: honest page cap and testable lab extraction flow
- Commit
1f69a1a98655d8cf674a7b2b565260928d95938e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 04:36 UTC (8 hours ago)
- Parents
26a723d
Lab PDF import ran each page with budgets far below real inference time (fixed in the SDK and the OpenAssistant service), and pages past the 50-page render cap were reported as 'could not be rendered' even though they were never tried. - Pages now render at 1024 px, the vision tower's decode side, instead of 1240 px that both sides then downscaled anyway. - The renderer returns capped pages separately and the import reports them honestly in the review failures: how many pages the PDF has, that only the first 50 were read, and which page range was not extracted. Nothing is silently truncated. - Per-page calls stay (deliberately not one batched call): the service keeps one warm model session across pages, each page keeps its own reply-token budget and page attribution, and a slow or failing page is reported for that page instead of sinking the whole document. The loop is now an extractable seam (extractLabResults) with no fake results on failure. Tests: delayed fake extraction completes all pages with page attribution, a failing page is reported and later pages still run, malformed rows count as rejected, and the cap notice wording/range is pinned.
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex 176e17a77e..71528219f2 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -16,7 +16,7 @@ _Install: ./install health (dev by default)._ - Per-metric dashboards with charts/history (`GenericLineChart`/`GenericBarChart`, hypnogram for sleep) - Medications carry their own dosage timing (dose times/repeat) and an optional planned end date (shown only while Taking), with exact reminders as a literal on/off toggle on the medication record (`DoseScheduler`, `DoseSoundService`, boot-rescheduled; reminders fire per the medication timing and stop after its planned end date — there is no separate reminder schedule/end date); vaccinations from bundled CVX, drugs from RxNorm; card attachments (PDF/photo) - Food logging against a bundled database + search API; AI insights via the on-device OpenAssistant model; file export-**Architecture / data-flow:** Dialogs that act on a record/metric are `Route.…Dialog` destinations (`DialogPage()` entries in `ui/NavigationEntries.kt`) pushed from clicks, with stateless content under `ui/dialogs/`; the ingredient search→quantity chain in `RecipeEditorPage` is the one local exception (see its `DIALOG LOCAL EXCEPTION` marker). Screenshot coverage lives in `src/screenshotTest` `MetadataPreviews` (stateless screens: Today/Nutrition/Body/metric detail/nutrition breakdown/recipe list+editor/sleep/exercise + date-time and simple dialog routes); VM-draft routes are exempted per-route in `Route.kt`. `ui/` Today + record pages → `platform/MedicalViewModel` (+ per-area `Medical*Ops`) → `data/HealthRepository` over Room (`Record`, `MedicalRecords`; dosage timing/planned end/reminder toggle are columns on `MedicationEntry`) synced with Health Connect; `domain/` holds pure FHIR (Observations, Medication, Immunization, Allergy/Condition) + `DoseSchedule` (next-dose arithmetic over a `MedicationEntry`); reminders flow `DoseScheduler` (armed per medication) → receivers → `DoseReminderActivity` + `service/DoseSoundService`. DB is v14 (migration 13→14 adds `LabDocument`, `LabTestCatalogEntry` and `LabResultEntry.sourceDocumentId/sourcePage/panel`); the medication timing/end/toggle columns live on `MedicationEntry`. Lab PDF import: Medical tab FAB → `MedicalLabImportOps.startLabPdfImport` stores the PDF in `files/lab_documents/` (backed up via `AppBackupAgent`), renders pages health-locally with platform `PdfRenderer` (`LabPdfRenderer`; the Rust engine is :pdf-app-private), extracts per page via `sdk:openassistant` `generateJsonWithImages` + `domain/LabExtraction` schema/clamping, and writes only on confirm in `Route.LabImportReview` (dedupe by normalized test+date+value; unmatched tests become `LabTestCatalogEntry` rows). Deleting a PDF keeps its results, whose source link then reports it gone. The lab-test picker (`CatalogKind.LabTest`) lists a merged catalogue — recorded tests, custom catalogue rows, bundled LOINC names/units from `ReferenceCatalog` (no invented reference ranges) — and pre-fills unit/range where known.+**Architecture / data-flow:** Dialogs that act on a record/metric are `Route.…Dialog` destinations (`DialogPage()` entries in `ui/NavigationEntries.kt`) pushed from clicks, with stateless content under `ui/dialogs/`; the ingredient search→quantity chain in `RecipeEditorPage` is the one local exception (see its `DIALOG LOCAL EXCEPTION` marker). Screenshot coverage lives in `src/screenshotTest` `MetadataPreviews` (stateless screens: Today/Nutrition/Body/metric detail/nutrition breakdown/recipe list+editor/sleep/exercise + date-time and simple dialog routes); VM-draft routes are exempted per-route in `Route.kt`. `ui/` Today + record pages → `platform/MedicalViewModel` (+ per-area `Medical*Ops`) → `data/HealthRepository` over Room (`Record`, `MedicalRecords`; dosage timing/planned end/reminder toggle are columns on `MedicationEntry`) synced with Health Connect; `domain/` holds pure FHIR (Observations, Medication, Immunization, Allergy/Condition) + `DoseSchedule` (next-dose arithmetic over a `MedicationEntry`); reminders flow `DoseScheduler` (armed per medication) → receivers → `DoseReminderActivity` + `service/DoseSoundService`. DB is v14 (migration 13→14 adds `LabDocument`, `LabTestCatalogEntry` and `LabResultEntry.sourceDocumentId/sourcePage/panel`); the medication timing/end/toggle columns live on `MedicationEntry`. Lab PDF import: Medical tab FAB → `MedicalLabImportOps.startLabPdfImport` stores the PDF in `files/lab_documents/` (backed up via `AppBackupAgent`), renders pages health-locally with platform `PdfRenderer` (`LabPdfRenderer`; the Rust engine is :pdf-app-private), renders at 1024 px (the vision tower's decode side), caps at 50 pages with the cap reported in the review failures, extracts per page via `sdk:openassistant` `generateJsonWithImages` + `domain/LabExtraction` schema/clamping, and writes only on confirm in `Route.LabImportReview` (dedupe by normalized test+date+value; unmatched tests become `LabTestCatalogEntry` rows). Deleting a PDF keeps its results, whose source link then reports it gone. The lab-test picker (`CatalogKind.LabTest`) lists a merged catalogue — recorded tests, custom catalogue rows, bundled LOINC names/units from `ReferenceCatalog` (no invented reference ranges) — and pre-fills unit/range where known. **Entry points + reading order:** `MainActivity.kt` → `ui/TodayPage.kt` → `platform/MedicalViewModel.kt` → `data/HealthRepository.kt` → `domain/FhirRecords.kt` → `platform/DoseScheduler.kt`. **Gotchas:** - Day views use half-open local-calendar ranges (`HealthChartData.dayRange`, DAO `startTime in [start, end)`, bucketed by start): DST days are 23/25h, midnight point records belong to the new day, and intervals crossing midnight count on their start day. Day-tab line metrics average their hourly averages; bar metrics sum their hourly sums; basal metabolic rate (stored kcal/day) is an averaged line metric, while Today hydration converts stored litres to ml. Month/year tabs bucket bar metrics into weekly/monthly sums: their per-day average divides the period total by the calendar days in the month/year, and a history row's goal is the daily goal scaled by the days its bucket covers (line metrics keep averaging and comparing bucket averages directly).
health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt b/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.ktindex c94ab16906..85822e4b8d 100644--- a/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt@@ -19,9 +19,19 @@ import java.io.File object LabPdfRenderer { private const val TAG = "LabPdfRenderer" const val MAX_PAGES = 50- private const val TARGET_WIDTH = 1240 - data class Rendered(val pageCount: Int, val images: List<File>, val failedPages: List<Int>)+ // The vision tower decodes at most a 1024 px side (MamlChatEngine's+ // MAX_IMAGE_SIDE provider-side), so rendering wider only bought a+ // larger PNG decode/encode on both sides of the IPC.+ private const val TARGET_WIDTH = 1024++ data class Rendered(+ val pageCount: Int,+ val images: List<File>,+ val failedPages: List<Int>,+ /** Pages past [MAX_PAGES]: not rendered, reported honestly as capped, never as render failures. */+ val cappedPages: List<Int> = emptyList(),+ ) @Suppress("TooGenericExceptionCaught") fun render(context: Context, pdf: File): Rendered {@@ -56,10 +66,8 @@ object LabPdfRenderer { failed.add(index + 1) } }- if (count > MAX_PAGES) {- for (p in MAX_PAGES + 1..count) failed.add(p)- }- return Rendered(count, images, failed)+ val capped = if (count > MAX_PAGES) (MAX_PAGES + 1..count).toList() else emptyList()+ return Rendered(count, images, failed, capped) } finally { runCatching { renderer?.close() } runCatching { descriptor?.close() }
health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.ktindex 909dacf444..787a92f38e 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt@@ -54,22 +54,27 @@ fun MedicalViewModel.startLabPdfImport(uri: Uri) { return@launch } val failures = rendered.failedPages.map { "Page $it could not be rendered." }.toMutableList()- val results = mutableListOf<ExtractedLabResult>()- var rejected = 0- for (image in rendered.images) {- val page = image.nameWithoutExtension.removePrefix("page-").toIntOrNull() ?: continue- try {- val raw = assistant.generateJsonWithImages(- LabExtraction.prompt(page), LabExtraction.SCHEMA, listOf(image.absolutePath),- )- val parsed = LabExtractionParser.parse(raw, page)- results += parsed.results- rejected += parsed.rejectedRows- } catch (e: Exception) {- failures += "Page $page: ${e.message ?: "extraction failed"}"- }+ cappedPagesFailure(rendered)?.let { failures += it }+ val pages = rendered.images.mapNotNull { image ->+ image.nameWithoutExtension.removePrefix("page-").toIntOrNull()?.let { it to image }+ }+ // One extraction call per page, sequentially, on purpose:+ // the service keeps one warm model session across calls, each+ // page gets its own reply-token budget and its results stay+ // attributable to that page, and a slow or failing page is+ // reported for that page instead of sinking the whole document.+ // Sending every page in one call would share one reply budget+ // and one context across the document and lose page attribution.+ val extraction = extractLabResults(pages) { page, image ->+ assistant.generateJsonWithImages(+ LabExtraction.prompt(page), LabExtraction.SCHEMA, listOf(image.absolutePath),+ )+ }+ val results = extraction.results+ failures += extraction.failures+ if (extraction.rejected > 0) {+ failures += "${extraction.rejected} extracted row(s) were malformed and dropped." }- if (rejected > 0) failures += "$rejected extracted row(s) were malformed and dropped." if (results.isEmpty()) { failLabImport( app, imported.fileName,@@ -97,6 +102,50 @@ fun MedicalViewModel.startLabPdfImport(uri: Uri) { } } +/** Honest cap notice for a PDF longer than [LabPdfRenderer.MAX_PAGES], or null when nothing was capped. */+internal fun cappedPagesFailure(rendered: LabPdfRenderer.Rendered): String? =+ if (rendered.cappedPages.isEmpty()) {+ null+ } else {+ "This PDF has ${rendered.pageCount} pages; only the first " ++ "${LabPdfRenderer.MAX_PAGES} were read. Pages ${rendered.cappedPages.first()}–" ++ "${rendered.cappedPages.last()} were not extracted."+ }++/** Outcome of extracting every rendered page: what parsed, what failed per page, what was dropped. */+internal data class LabPageExtraction(+ val results: List<ExtractedLabResult>,+ val failures: List<String>,+ val rejected: Int,+)++/**+ * Runs [extract] once per (page, image) in order and collects the outcome.+ * A page that throws (including the assistant's explicit timeout error) is+ * reported for that page and extraction continues with the next one; no+ * page's failure is hidden and no results are invented for it. Split out+ * so the flow is testable with a fake extractor — the production extractor+ * is OpenAssistant vision inference, which needs a device and a model.+ */+internal suspend fun extractLabResults(+ pages: List<Pair<Int, java.io.File>>,+ extract: suspend (page: Int, image: java.io.File) -> String,+): LabPageExtraction {+ val results = mutableListOf<ExtractedLabResult>()+ val failures = mutableListOf<String>()+ var rejected = 0+ for ((page, image) in pages) {+ try {+ val parsed = LabExtractionParser.parse(extract(page, image), page)+ results += parsed.results+ rejected += parsed.rejectedRows+ } catch (e: Exception) {+ failures += "Page $page: ${e.message ?: "extraction failed"}"+ }+ }+ return LabPageExtraction(results, failures, rejected)+}+ private fun MedicalViewModel.failLabImport(app: Context, fileName: String?, message: String) { fileName?.let { LabDocumentStore.delete(app, it) } labImportStateFlow.value = MedicalViewModel.LabImportState(
health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt b/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.ktindex 51eb5167f6..c6b70f08f2 100644--- a/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt@@ -41,6 +41,54 @@ class LabImportOpsTest { repeat(200) { Shadows.shadowOf(Looper.getMainLooper()).idle(); if (cond()) return; delay(5) } } + // Slow pages must complete through the extraction flow: the fake pays+ // a delay per page (the shape of real on-device inference, which the+ // old 45 s service / 60 s SDK budgets cut off) and every page's rows+ // still arrive, attributed to their own page.+ @Test fun delayedPagesCompleteThroughExtractionFlow() = runTest {+ val pages = (1..3).map { page -> page to java.io.File("page-$page.png") }+ val out = extractLabResults(pages) { page, _ ->+ delay(50)+ """{"results":[{"name":"Test$page","value":$page,"unit":"mg/dL"}]}"""+ }+ assertEquals(listOf("Test1", "Test2", "Test3"), out.results.map { it.name })+ assertEquals(listOf(1, 2, 3), out.results.map { it.page })+ assertTrue(out.failures.isEmpty(), out.failures.toString())+ assertEquals(0, out.rejected)+ }++ @Test fun failedPageIsReportedAndOtherPagesContinue() = runTest {+ val pages = (1..3).map { page -> page to java.io.File("page-$page.png") }+ val out = extractLabResults(pages) { page, _ ->+ if (page == 2) throw IllegalStateException("OpenAssistant did not respond within 330 seconds")+ """{"results":[{"name":"Test$page","value":$page}]}"""+ }+ assertEquals(listOf("Test1", "Test3"), out.results.map { it.name })+ assertEquals(1, out.failures.size)+ assertTrue(out.failures.single().startsWith("Page 2:"), out.failures.toString())+ assertTrue(out.failures.single().contains("did not respond"), out.failures.toString())+ }++ @Test fun malformedRowsCountAsRejectedNotResults() = runTest {+ val out = extractLabResults(listOf(1 to java.io.File("page-1.png"))) { _, _ ->+ """{"results":[{"value":3},{"name":"Glucose","value":95}]}"""+ }+ assertEquals(listOf("Glucose"), out.results.map { it.name })+ assertEquals(1, out.rejected)+ }++ @Test fun cappedPagesAreReportedAsCapNotRenderFailure() {+ val capped = LabPdfRenderer.Rendered(+ pageCount = 57, images = emptyList(), failedPages = emptyList(), cappedPages = (51..57).toList(),+ )+ val message = cappedPagesFailure(capped)+ assertTrue(message!!.contains("57 pages"), message)+ assertTrue(message.contains("51–57"), message)+ assertTrue(message.contains("not extracted"), message)+ val uncapped = LabPdfRenderer.Rendered(pageCount = 3, images = emptyList(), failedPages = emptyList())+ assertEquals(null, cappedPagesFailure(uncapped))+ }+ @Test fun confirmationGateWritesLinkageAndDedupes() = runTest { val vm = vm() val result = ExtractedLabResult(