Skip to content

test: make a stalled AlertStateStoreTest fail fast and explain itself - #360

Merged
nofuturekid merged 11 commits into
mainfrom
fix/alert-state-store-hang
Nov 13, 2026
Merged

nofuturekid merged 11 commits into
mainfrom
fix/alert-state-store-hang

Conversation

@nofuturekid

@nofuturekid nofuturekid commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Diagnostic only. This does not fix the hang in #359, because its cause is not proven.

One full local run hung for about 34 minutes in AlertStateStoreTest.remove_forgets_only_that_server. The thread dump showed every thread idle and no lock held, so a coroutine is suspended and nothing resumes it. Two hypotheses are open:

  • H1: an edit whose caller dispatcher cannot run (for example Dispatchers.Main while the Robolectric main thread is blocked in runBlocking) keeps DataStore's coordinator mutex locked, so every later edit in that JVM waits for ever.
  • H2: a resumption into the main thread's blocking event loop (the test's runBlocking) never arrives, and nothing holds the mutex.

The first version of StallWatch could not decide between them. This version can. When a watched test has not finished after 60 s it writes a dump to app/build/stall-dumps/ (and to stderr, and a copy into the HTML test report directory) and ends the test JVM. The dump now has:

  • the watched test classes started in this JVM so far, in order (classes without the rule are not listed), each with the highest coroutine id alive when it started;
  • every live coroutine (kotlinx-coroutines-debug probes) with state, dispatcher, suspension point, creation stack and the test class during which it was created, plus a summary: which coroutine passes through SingleProcessCoordinator.lock (holds the mutex) and where it is suspended, which edits wait for DataStore and on which dispatcher, which coroutines never started, and what each runBlocking is suspended on, with its event loop queue. Every coroutine named in the summary is printed in full; the cap of 150 applies only to the others, newest first, and the dump says how many were left out;
  • the main looper's pending messages, the thread stacks, and the DataStore internals (is the coordinator mutex locked, what is queued for the write actor).

How to read it:

  • H1: a coroutine holds the mutex (suspended in transformAndWrite), the mutex is locked, and an edit caller sits on a dispatcher that is not served (for example a looper with a pending message in the main looper queue). A second shape of H1: the transform of the test's own edit is lost on its own runBlocking; then one holder exists and the only edit caller is on the BlockingEventLoop.
  • H2: the runBlocking coroutine is suspended, no coroutine holds the mutex, the mutex is unlocked and no edit caller exists.
  • The event loop queue of the runBlocking does not separate the two: it is empty in the H1 validation run as well.
  • AlertStateStoreTest.setUp ends with an unconditional clear() edit, and it finished in the original hang. Under H1 the blocking edit therefore entered the write actor after setUp, from a coroutine that was still running then.

What the dump cannot tell: with two or more edit callers on unserved dispatchers, which one is in flight; the value of the in-memory data, so within H2 not "answer never completed" versus "completed, resumption lost"; and a coroutine on an abandoned dispatcher that nothing else references can be missing from the list (the probes hold coroutines weakly), while the mutex state and the actor queue are still shown.

The rule is now on every test class that uses the sandbox-wide DataStore (one Context.dataStore delegate, SettingsStore.kt:31): AlertCheckRunnerTest, AlertCheckWorkerTest, AlertSchedulerTest, AlertSettingsStoreTest, AlertStateStoreTest, SaveServerPinTest, UnraidGatewayTest, UpdateCheckOnForegroundTest. A coroutine leaked by an earlier class is caught in the class where it bites. Its creation stack names that class only if it passes through test code, which a coroutine started from another coroutine does not; so the dump also says, per coroutine, during which watched class it was created. It is not a retry and not a longer timeout: 60 s is far above any honest test (the longest watched class takes about 4 s in total), and the JVM is ended because after a stall every later test that touches the DataStore would wait for ever too.

Files and regions touched:

  • StallWatch.kt: coroutine dump, started-classes list, report-directory copy; the watchdog waits on a deadline loop and writes the dump on a bounded thread, so a blocked read cannot keep the JVM alive.
  • One import (org.junit.Rule) and one line @get:Rule val stallWatch = StallWatch() at the top of each of the seven other classes above (AlertStateStoreTest already had it).
  • gradle/libs.versions.toml, app/build.gradle.kts: kotlinx-coroutines-debug as a testImplementation, same kotlinxCoroutines version ref as the coroutines in use (1.11.0); and a system property for the report-directory copy, set at execution time.

No production code changes. Nothing under .github/ changes: the test job already uploads app/build/reports/tests/testDirectDebugUnitTest as artifact test-report with if: always(), and the dump copy lands in stall-dumps/ inside that directory (checked: it is still there after the JVM was ended and Gradle wrote its report).

One thing that did not work

Installing the probes from the test (DebugProbes.install()) succeeds and records nothing: Robolectric loads kotlinx.coroutines into its sandbox class loader but leaves the Kotlin standard library, which holds the hook DebugProbesKt, in the application class loader, and the hook calls the DebugProbesImpl of its own loader. The rule therefore installs the probes through the application class loader (reflection); the hook then reports every coroutine of the sandbox. If the install fails the reason is printed in the dump and no test fails. Coroutines created before the first watched class starts (AlertCheckRunnerTest in the current order) are not recorded.

What was measured

  • Validation with a throw-away test (not part of this PR), limit lowered to 8 s: an edit launched on Dispatchers.Main.immediate, then a second edit in runBlocking on the Robolectric main thread. Gradle reported Process 'Gradle Test Executor 1' finished with non-zero exit value 70, and the dump says:
    • holds the DataStore coordinator mutex (stack passes through SingleProcessCoordinator.lock): 1 / #1 SUSPENDED on Dispatchers.IO, suspended at androidx.datastore.core.DataStoreImpl$transformAndWrite$2$1.invokeSuspend(DataStoreImpl.kt:435)
    • edits waiting for DataStore's answer ...: 2 / #0 on Dispatchers.Main.immediate / #2 on BlockingEventLoop@...
    • for #0, created at: ... StallValidationTest.leakedByAnEarlierTest(StallValidationTest.kt:25)
    • main looper queue: ... Message 0: { when=0 callback=kotlinx.coroutines.internal.DispatchedContinuation target=android.os.Handler }
    • SingleProcessCoordinator.mutex = ...[isLocked=true,owner=null] and, for the runBlocking coroutine, EventLoopImplBase._queue$volatile = null.
  • Cost in a normal run (same machine and container, :app:testDirectDebugUnitTest --rerun-tasks, class times from the JUnit XML): the eight watched classes together took 7.9 s before and 7.9 s after; the only visible difference is AlertCheckRunnerTest, the first watched class, 1.0 s to 1.9 s (installing the probes, once per JVM). AlertStateStoreTest: 0.17 s before, 0.15 s after.
  • Not proven: that any of this explains the original hang. The next stall will.

If you see a stall: copy app/build/stall-dumps and app/build/test-results out of the checkout (or download the test-report artifact of the failed CI job) BEFORE any rerun, attach them to #359, and do not rerun first. A rerun deletes them.

Linked issue / ADR

Refs #359. It stays open until a recurrence is explained by the dump.

Checklist

  • ./scripts/local-ci.sh green locally: LOCAL CI PASSED in 40s on the latest commit, 579 unit tests, 0 failures, 0 skipped (earlier a first run on the same commit failed in lintAnalyzeDirectDebugUnitTest because a generated KSP file of the release variant was missing while lint ran; the rerun passed)
  • Appearance change? No.
  • User-facing? No (tests only), no CHANGELOG.md entry.
  • Commits are signed and the branch is rebased on main

🤖 Generated with Claude Code

@nofuturekid nofuturekid added this to the 0.1.49 milestone Nov 13, 2026
nofuturekid and others added 11 commits November 13, 2026 22:31
The Resume button on a paused container sent the start mutation, which
Docker refuses ("cannot start a paused container, try unpause instead"),
so the container stayed paused. A paused container now gets the existing
UnpauseContainer mutation (docker.unpause, available since API 4.29.0, so
on every supported server and without a capability floor); a stopped
container still gets start.

The choice is made once, in UnraidRepository.startContainer(client, id,
paused), the same seam as restartContainer. The Docker tab row and the
container sheet both go through MainViewModel.startContainer(Container).

The demo follows the repository surface: UnraidGateway.startContainer
takes the same flag, and the demo model refuses start on a paused
container like Docker does, so the demo no longer hides the bug.

Closes #345
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ain http

The foreground clients followed redirects, and OkHttp keeps the x-api-key
header when it does, so a 3xx answer moved the key to whatever Location
named: another host, or http after the user entered https. For the
WebSocket the handshake was followed and the key then went out in
connection_init to the new host.

No client that carries the key follows a redirect any more (ADR-0051).
A redirect is reported as the new reason Redirected, naming the target
origin ("The server redirects to https://... Edit the server and enter
that address."), in the tabs, in the Add server sheet's Test and in the
action message. It is no connection problem, so the pill does not say
Offline. Unraid answers http requests with 302 when SSL is Yes or Strict.

Closes #354

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A key without the permission for an action no longer gets the button for it.
The Docker, VMs and Array tabs and the container, VM and notification sheets
hide Start, Stop, Restart, Update, parity, Archive and Delete controls when the
capability probe says the key lacks DOCKER, VMS, ARRAY or NOTIFICATIONS
UPDATE_ANY / DELETE_ANY, and show one "View only" note that names the missing
permission, with a link to the README table. Unknown access keeps every button
as before, and a refused action now says which permission it needed instead of
"Forbidden resource".

The Add server Test button now uses the capability probe instead of Ping, which
the server answers for any key: a rejected key fails the test, and an accepted
one reports the Unraid and API version and what the key can do. The API Key field
gets a hint and a "Which permissions?" link.

The Overview shows the failure reason of a total failure like the tabs do, and
only a connection problem (unreachable server, rejected key) marks it offline and
hides the needs-attention card.

Closes #315
Closes #316

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ion card with services off

The Containers and Virtual machines cards turned an unknown list (not loaded,
turned off, not allowed, offline) into "0 running", "all healthy" and
"0 configured". They now show the same dash as the other Overview cards; a real
empty list still reads 0. The figures moved into OverviewFigures.kt so they can
be unit-tested.

Regression tests for #356: the Needs attention card stays with VMs or Docker
switched off or forbidden for the key, and the cards render dashes while their
data is unknown. ErrorReasonTest now also classifies the Docker-off answer
through the real Docker query.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Settings, Notifications gets the switch for the background check that
already exists on main (ADR-0048), off by default.

- Switching on opens an explanation, then asks for POST_NOTIFICATIONS on
  Android 13 and later; only a granted answer schedules anything. A
  denial leaves the switch off and shows that Android blocks
  notifications for NOVA, with a button to Android's notification
  settings. The line is re-read when the screen returns to the front.
- Interval (15 minutes to 3 hours), level (alerts and warnings, or
  alerts only) and Wi-Fi only go through AlertScheduler.update, which
  reschedules the existing work. The screen reads only the settings store
  and never asks for WorkManager while alerts are off.
- "Send test notification" runs the same https-only probe once for the
  active server and posts its newest unread alert or warning. It never
  writes the remembered state.
- Each server has a last-check line: the outcome and time are now kept
  in ServerAlertState.lastCheck, set by the check runner after every run
  and read by the screen only; what is notified does not change. A
  server with only http addresses reads "not checked in the background
  because the connection is not encrypted. An https address is needed.";
  the demo server is named as never checked.
- A battery hint and a link to dontkillmyapp.com (opened by the user), and
  a link to the README recipe for instant alerts with Unraid's own agents.

Documents: CHANGELOG, README (feature list and an Alerts section), privacy
policy (what is sent in the background, the https rule, the new
permissions, the alert state), the project site, the store description,
HANDOFF, and an addendum to ADR-0048 for the https and demo rules.

Closes #321

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- Settings, Notifications: say so when the user switched off the "Server
  alerts" or "Server warnings" channel (AlertNotifier.blockedChannel, read
  only), with the same button to Android's notification settings.
- Switching alerts off cancels a running test and a test that finishes after
  the switch is off posts nothing.
- Robolectric tests for both.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
#358 moved the Add server sheet's Test onto the capability probe, whose
failure path never called redirectMessage(): a 3xx answer showed the generic
"Http request failed with status code 302" instead of the sentence ADR-0051
documents. testOutcomeOf now prefers the redirect message when the probe's
failure carries the HTTP exception. Tests: a 302 with a target and one
without go through the real probe; the classifier test no longer claims to
cover Test. ADR-0048's last sentence pointed at in-app clients that follow
redirects; since ADR-0051 they do not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
ADR-0051, decision 4, said that classifyResponse returns the redirect
sentence so the Add server sheet's Test shows it without a change of its
own. Test no longer goes through classifyResponse: testConnection runs
testOutcomeOf(probeCapabilities(...)), and testOutcomeOf prefers the
redirect message of the probe's failure cause. Tabs still get the reason
through classifyErrorReason and toQueryError, and the snackbar of a failed
action gets the lower-cased sentence from checkActionResponse.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
One full local run hung for over 34 minutes in AlertStateStoreTest with every
thread idle, so the dump could not say which coroutine waited for what.
StallWatch writes the thread stacks, the main looper state and the DataStore
internals (lock, write actor, in-memory cache) after 60 s and ends the test
JVM, so a recurrence fails within a minute with the data needed to decide
the cause. Diagnostic only, not a fix for the hang.

Refs #359

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…at uses the DataStore

The stall dump of #359 could not tell the two open hypotheses apart: it
showed threads, the main looper and DataStore fields, but not which
coroutine holds the DataStore mutex or what the test's runBlocking waits on.

- StallWatch installs kotlinx-coroutines-debug probes once per JVM and
  dumps every live coroutine with state, dispatcher, suspension point and
  creation stack, names the coroutine that passes through
  SingleProcessCoordinator.lock, lists the edit callers and their
  dispatchers, shows the main looper's queue and the event loop of each
  runBlocking, and lists the test classes started in this JVM so far.
  The probes are installed through the application class loader:
  Robolectric keeps the Kotlin standard library there, so a sandbox-side
  install records nothing.
- The rule is now on every class that uses the sandbox-wide DataStore
  (AlertCheckRunnerTest, AlertCheckWorkerTest, AlertSchedulerTest,
  AlertSettingsStoreTest, SaveServerPinTest, UnraidGatewayTest,
  UpdateCheckOnForegroundTest, AlertsSectionTest, AlertStateStoreTest), so a coroutine leaked
  by an earlier class is caught where it bites and its creation stack names
  its origin.
- The dump is also written next to the HTML test report, which CI already
  uploads when a job fails.
- kotlinx-coroutines-debug as test dependency, same version as the
  coroutines in use.

Still no fix and no retry: the 60 s limit only turns a silent hang into a
fast failure with evidence.

Refs #359

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… test class

The coroutine dump listed details for the 150 oldest coroutines only,
but the coroutines at fault (mutex holder, edit callers, never-started
ones) are the newest. Every coroutine named in the summary is now
printed in full; the cap applies to the rest, newest first, with the
number left out.

Each watched class records the highest coroutine id alive when it
starts, and the dump says for every coroutine during which class it was
created, so a coroutine leaked by an earlier class is attributable even
when its creation stack names no test.

The watchdog waits on a deadline loop (no early end on a spurious
wakeup), writes the dump on a bounded thread (a blocked read cannot
keep the JVM alive) and lists the thread stacks first. The KDoc now
states how the dump reads under each hypothesis and what it cannot
tell.

Refs #359

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@nofuturekid
nofuturekid force-pushed the fix/alert-state-store-hang branch from bc280d0 to deded38 Compare November 13, 2026 22:12
@nofuturekid
nofuturekid merged commit deded38 into main Nov 13, 2026
11 checks passed
@nofuturekid
nofuturekid deleted the fix/alert-state-store-hang branch November 13, 2026 22:21

This branch was successfully deployed

1 active deployment
github-pages — deded389 Deployed Nov 13, 2026 by nofuturekid via deploy #14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant