feat(sdk): explicit Tor lifecycle — Wire.shutdown / flush / torState + observable state #49

Merged
sirius merged 3 commits from feat/tor-lifecycle into main 2026-09-12 20:58:31 +00:00
Owner

What

The UniFFI SDK had no lifecycle: Wire was a bare handle over a Node with no
stop, no flush, and no way to ask where the onion service was. On Android the
process is killed without warning by Doze and the background-process killer, so
"drop everything when the process dies" is not a shutdown strategy.

This PR adds the missing verbs, end to end:

Layer New API Meaning
Kotlin (Wire) shutdown() Bounded outbox drain, stop the onion service, abort the retry worker, checkpoint the WAL, drop the node.
Kotlin (Wire) flush(): FlushOutcome One delivery attempt for every queued outbox row, ignoring backoff, then checkpoint. Reports attempted / delivered / remaining.
Kotlin (Wire) torState(): TorState Where the onion service is right now.
Kotlin (enum) TorState BOOTSTRAPPING, PUBLISHED, DEGRADED_REACHABLE, STOPPED.
Rust (Node) Node::shutdown(), Node::flush() -> FlushOutcome, Node::tor_state() -> TorState Same contract, no UniFFI in the way.
Rust (hs) TorState, tor_state_of(State, stopped, reachable) The status projection, unit-tested against every Arti variant.

Errors stay typed: WireError gains a second flat variant Stopped { message }
(WireException.Stopped in Kotlin), so "you must unlock again" is a distinct UI
state from Failed (network/protocol). No unwrap() on a poisoned mutex
anywhere — a poisoned handle reports Stopped, which is the correct recovery
anyway (unlock again).

Kotlin signatures (generated)

suspend fun Wire.shutdown()
suspend fun Wire.flush(): FlushOutcome          // attempted/delivered/remaining: UInt
fun Wire.torState(): TorState                   // sync: no I/O, safe from a UI thread
enum class TorState { BOOTSTRAPPING, PUBLISHED, DEGRADED_REACHABLE, STOPPED }

Exact teardown contract (child cards: t_5bf32cd3, t_f46a9863)

  • Node::shutdown() is idempotent: a second call returns Ok(()).
  • Wire.shutdown() is safe to call twice, but the second call returns the typed
    WireException.Stopped — the handle is spent, and a silent Ok would hide a
    double-teardown bug. Treat Stopped as success.
  • Every method on a spent Wire (including send) throws
    WireException.Stopped. Wire.torState() returns STOPPED (it does not throw).
  • flush() on a spent handle throws WireException.Stopped.

Before / after on Android

Before: WireViewModel.lock() set wire = null and Phase.Locked, and
onCleared() did not exist. Dropping the Kotlin reference did not stop
anything — Arti kept its client and the hosted v3 onion service alive, the
outbox worker kept dialing peers, and the sqlite connection stayed open until the
JVM collector got around to the JNI handle. Nothing told the network the node was
gone; the onion service simply answered until the process died.

After: lock() and onCleared() both go through stopNode(Wire):

  1. flush() — one last bounded drain, so a queued message gets its chance
    before the process may lose its socket.
  2. shutdown() — drain again (10s budget), drop the onion service (rendezvous
    task aborted), abort the outbox retry worker (WorkerHandle now lives in a
    Mutex<Option<…>> so it can be aborted, not just dropped at the end of
    Node), checkpoint the sqlite WAL, and take the node handle out of the
    Wire.

Dropping the handle is what releases the last Arc to the Tor client and the
store, so Arti's runtime and the sqlite connection actually go away when the UI
does. Both steps run on a process-scoped TEARDOWN scope because onCleared()
runs after viewModelScope is cancelled. unlock() joins that teardown
before opening again — the old node holds the sqlite file and Arti's state lock
until shutdown() returns, and racing it made the next open fail.

A process killed outright never runs any of this. That is exactly why the
outbox lives in sqlite (parent card) and why flush() exists.

Why the WAL checkpoint is a second connection

Store owns its Connection and does not lend it out, and src/store.rs is
explicitly out of this card's scope. A checkpoint is a property of the
database, not of one connection, so checkpoint_wal() opens a short-lived
second connection to onionwire.db and runs PRAGMA wal_checkpoint(TRUNCATE).
It needs no passphrase (it moves committed pages; it does not decrypt them), it
is best-effort (a failure is logged, never fatal — WAL replay on open recovers
anything committed), and it is covered by an offline test against a real WAL:
src/node.rs::lifecycle_tests::checkpoint_wal_truncates_a_live_wal.

⚠️ Forward-looking caveat — SQLCipher (#43/PR merged on main before this
branch's base)
: on an encrypted store the key lives only inside Store, so a
second plain connection cannot read the file at all. The helper detects that
(SQLITE_NOTADB → "store is SQLCipher-encrypted — skipped") instead of
reporting a bogus error, and nothing is lost — sqlite folds the WAL into the db
when the last connection closes — but the explicit truncation has to move inside
Store to happen there. Follow-up card t_65c73d5a filed for the store owner
(Store::checkpoint_wal()), rather than reaching into a file this card forbids.

Base branch

Rebased onto main @ c39259b (the parent outbox PR #45 is merged, and
this branch now carries the keystore WireViewModel from main, not the older
one). Diff against main is exactly 6 files / 834 insertions:

38fde75 feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state
c068e29 feat(android): stop the node when the UI goes away
48c06df docs(sdk): Wire::shutdown doc said the second call returns Ok; it returns Stopped

Child cards stack here: t_5bf32cd3 (foreground service) and t_f46a9863
(Android outbox UI — it wants Wire.flush() / FlushOutcome).

The bug the live test caught (read this one)

The first tor_state() implementation projected Arti's raw combined status.
tests/tor_lifecycle.rs — run for real against the Tor network, not just
--ignored — failed with:

assertion `left == right` failed: start returns once the onion service is published
  left: Bootstrapping
 right: Published

Two distinct reasons, both device-visible:

  1. wait_until_published accepts either a ready status or a successful
    probe of our own onion — that mismatch is the whole reason the 360s publish
    wait exists. Arti's combined status can sit at Bootstrapping for minutes
    after the descriptor is already downloadable, so a node friends could reach
    reported "still starting".
  2. A freshly launched service reports Shutdown before its publish reactor
    starts (visible in the log: Shutdown for ~4s, then Bootstrapping, then
    probe ok). Projecting that to Stopped would make every unlock briefly
    look like a dead node — the worst possible answer from a lifecycle API.

Fix: Node keeps an onion_reachable flag (AtomicBool) set when the publish
bar is crossed in start/rotate and cleared when rotate hard-cuts the old
service. tor_state_of(state, stopped, reachable) then mirrors hs_is_ready
exactly: Running → Published, DegradedReachable → DegradedReachable,
Broken/Shutdown on a live node → Bootstrapping (transient, not terminal),
Bootstrapping/DegradedUnreachable + reachable → Published, and only the
explicit stop flag (or a stopped service) yields Stopped. Covered by
tests/hs.rs::reachable_statuses_report_published_while_arti_says_bootstrapping
and tor_state_maps_every_arti_status.

Verification (real output, head 48c06df, rebased onto main@c39259b)

$ cargo test --locked
     Running unittests src/lib.rs / src/main.rs + tests/{app_sig,backup,dispatch,file,hs,outbox,
     pay,profile,protocol,qr,ratelimit,rotate,rotate_hs,sanitize,send,store,tor_hs,tor_lifecycle,
     tui_chrome,tui_frames,tui_spec,two_node,wallet,wipe,zeroize}.rs + Doc-tests
     -> 28 suites, 217 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out
     (the 4 ignored are the live-Tor suites: tor_hs, two_node, rotate_hs, tor_lifecycle)
     cargo test exit=0

$ cargo clippy --locked --all-targets -- -D warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 52.31s        # clean
    clippy exit=0

$ cd crates/onionwire-sdk && cargo test
    tests::tor_state_of_a_stopped_handle_is_stopped ... ok
    tests::calls_after_shutdown_are_typed_errors_not_panics ... ok
    tests::tor_state_maps_every_core_state ... ok
    test result: ok. 3 passed   # + tests/init_provider.rs 1 passed, tests/provider_resolution.rs 1 passed

$ cargo test --locked --test tor_lifecycle -- --ignored --nocapture    # live Tor network
    […]4ad.onion hs status: Bootstrapping          # descriptor upload in flight, real Arti
    2026-09-12T19:34:46Z INFO tor_hsservice::publish::reactor: reuploading descriptor in 1h 19m …
    test shutdown_stops_the_node_and_later_calls_are_typed_errors ... ok
    test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 25.28s

$ cd android && CARGO_TARGET_DIR=… ./gradlew --no-daemon :app:assembleDebug
> Task :sdk:mergeDebugNativeLibs
> Task :app:stripDebugDebugSymbols
Unable to strip the following libraries, packaging them as they are: libonionwire_sdk.so.
> Task :app:compileDebugKotlin
> Task :app:assembleDebug

BUILD SUCCESSFUL in 4m 47s
61 actionable tasks: 15 executed, 46 up-to-date

Artifact (throwaway debug build, but it proves the toolchain and the regenerated
bindings):

-rw-r--r-- 47012672  android/app/build/outputs/apk/debug/app-debug.apk
sha256  d84cf7693ef0dab66e4570f2994ad86adf7fc977c1ac7d809da37614bd570891
  18552536  classes.dex
  34450376  lib/arm64-v8a/libonionwire_sdk.so
   = sha256 96234203d86ab2f43a2a78d65f88ab1c984c75673bfa78fb58918cdfb9953698 (byte-identical in size
     to the built aarch64-linux-android/release/libonionwire_sdk.so)

Generated Kotlin surface actually compiled into the AAR
(android/sdk/build/generated/uniffi/uniffi/onionwire_sdk/onionwire_sdk.kt):

1335:    suspend fun `flush`(): FlushOutcome
1407:    fun `torState`(): TorState
2189:enum class TorState { BOOTSTRAPPING, PUBLISHED, DEGRADED_REACHABLE, STOPPED }
2252:        class Stopped(message: String) : WireException(message)

CI: green on 48c06df2cff7a265cce2dcabdd33d878b9857f41 —
https://forgejo.siriusdevops.com/sirius/onionwire/actions/runs/174 (ci / test,
pull_request, cargo test --locked + cargo clippy --locked --all-targets -- -D warnings inside the rust container on the arm64 Pi runner).

Tests

Offline (runs in CI / cargo test):

  • tests/hs.rs — tor_state_maps_every_arti_status,
    stopped_outranks_whatever_arti_reports, ready_states_are_the_published_ones.
  • src/node.rs — checkpoint_wal_truncates_a_live_wal,
    checkpoint_wal_is_a_no_op_without_a_database.
  • crates/onionwire-sdk/src/lib.rs — tor_state_of_a_stopped_handle_is_stopped,
    calls_after_shutdown_are_typed_errors_not_panics,
    tor_state_maps_every_core_state.

Live Tor (#[ignore], same convention as tests/tor_hs.rs):

  • tests/tor_lifecycle.rs — starts a node, asserts Published, flushes an empty
    outbox, shuts down, asserts Stopped, asserts the second shutdown() and a
    post-shutdown flush() / send() / rotate() all return errors instead of
    panicking.

Naming decisions (as requested)

  • Wire.shutdown() / Node::shutdown() — not stop()/close(): it is a
    lifecycle transition, and Stopped is already the terminal state name.
  • Wire.flush() / Node::flush() — same word the TUI/card uses; returns
    FlushOutcome { attempted, delivered, remaining }.
  • Wire.tor_state() / Node::tor_state() — sync, read-only, no I/O.

Not in this PR

  • The README.md wording is deferred (PR #38 owns the file) — see below.
  • crates/onionwire-sdk/README.md still says "No outbox, no spool in v1" and
    its "Locked protocol facts" table predates the outbox. Both are outside this
    card's allowed files; suggesting it here rather than silently editing.
  • src/tui.rs / docs/TUI.md (PR #27) untouched.
  • Side effect worth noting: crates/onionwire-sdk did not compile on the
    base
    — Node::send returns Result<OutboxStatus, String> after #45 while
    the SDK still mapped it to Result<(), String>, so cargo build --release --lib failed with E0308. CI's path allowlist excludes crates/** from the
    Rust job, which is why #45's cargo test run stayed green. Fixed here.

README (deferred)

Exact wording to apply to README.md after #38 lands — a lifecycle paragraph
for the Android/SDK section:

Node lifecycle (Android SDK)

A node is explicit about starting and stopping:

val wire = openWire(filesDir.absolutePath + "/onionwire", passphrase) // published before it returns
wire.flush()        // deliver everything queued now (bounded, 30s)
wire.torState()     // BOOTSTRAPPING | PUBLISHED | DEGRADED_REACHABLE | STOPPED
wire.shutdown()     // drain, stop the onion service, checkpoint, release Tor

shutdown() is safe to call twice — the second call throws the typed
WireException.Stopped rather than panicking — and every call after it fails
the same way instead of touching a dead Tor client. Call it from your
ViewModel.onCleared() / service onDestroy(): the node must not outlive the
UI. Android can kill your process at any time without running either, which is
why queued chat sends live in sqlite and not in memory.

## What The UniFFI SDK had no lifecycle: `Wire` was a bare handle over a `Node` with no stop, no flush, and no way to ask where the onion service was. On Android the process is killed without warning by Doze and the background-process killer, so "drop everything when the process dies" is not a shutdown strategy. This PR adds the missing verbs, end to end: | Layer | New API | Meaning | |---|---|---| | Kotlin (`Wire`) | `shutdown()` | Bounded outbox drain, stop the onion service, abort the retry worker, checkpoint the WAL, drop the node. | | Kotlin (`Wire`) | `flush(): FlushOutcome` | One delivery attempt for every queued outbox row, ignoring backoff, then checkpoint. Reports `attempted` / `delivered` / `remaining`. | | Kotlin (`Wire`) | `torState(): TorState` | Where the onion service is right now. | | Kotlin (enum) | `TorState` | `BOOTSTRAPPING`, `PUBLISHED`, `DEGRADED_REACHABLE`, `STOPPED`. | | Rust (`Node`) | `Node::shutdown()`, `Node::flush() -> FlushOutcome`, `Node::tor_state() -> TorState` | Same contract, no UniFFI in the way. | | Rust (`hs`) | `TorState`, `tor_state_of(State, stopped, reachable)` | The status projection, unit-tested against every Arti variant. | Errors stay typed: `WireError` gains a second flat variant `Stopped { message }` (`WireException.Stopped` in Kotlin), so "you must unlock again" is a distinct UI state from `Failed` (network/protocol). No `unwrap()` on a poisoned mutex anywhere — a poisoned handle reports `Stopped`, which is the correct recovery anyway (unlock again). ### Kotlin signatures (generated) ```kotlin suspend fun Wire.shutdown() suspend fun Wire.flush(): FlushOutcome // attempted/delivered/remaining: UInt fun Wire.torState(): TorState // sync: no I/O, safe from a UI thread enum class TorState { BOOTSTRAPPING, PUBLISHED, DEGRADED_REACHABLE, STOPPED } ``` ### Exact teardown contract (child cards: `t_5bf32cd3`, `t_f46a9863`) * `Node::shutdown()` is **idempotent**: a second call returns `Ok(())`. * `Wire.shutdown()` is safe to call twice, but the second call returns the typed `WireException.Stopped` — the handle is spent, and a silent `Ok` would hide a double-teardown bug. Treat `Stopped` as success. * Every method on a spent `Wire` (including `send`) throws `WireException.Stopped`. `Wire.torState()` returns `STOPPED` (it does not throw). * `flush()` on a spent handle throws `WireException.Stopped`. ## Before / after on Android Before: `WireViewModel.lock()` set `wire = null` and `Phase.Locked`, and `onCleared()` did not exist. Dropping the Kotlin reference did **not** stop anything — Arti kept its client and the hosted v3 onion service alive, the outbox worker kept dialing peers, and the sqlite connection stayed open until the JVM collector got around to the JNI handle. Nothing told the network the node was gone; the onion service simply answered until the process died. After: `lock()` and `onCleared()` both go through `stopNode(Wire)`: 1. `flush()` — one last bounded drain, so a queued message gets its chance before the process may lose its socket. 2. `shutdown()` — drain again (10s budget), drop the onion service (rendezvous task aborted), abort the outbox retry worker (`WorkerHandle` now lives in a `Mutex<Option<…>>` so it can be aborted, not just dropped at the end of `Node`), checkpoint the sqlite WAL, and take the node handle out of the `Wire`. Dropping the handle is what releases the last `Arc` to the Tor client and the store, so Arti's runtime and the sqlite connection actually go away when the UI does. Both steps run on a process-scoped `TEARDOWN` scope because `onCleared()` runs *after* `viewModelScope` is cancelled. `unlock()` joins that teardown before opening again — the old node holds the sqlite file and Arti's state lock until `shutdown()` returns, and racing it made the next open fail. A process killed outright never runs any of this. That is exactly why the outbox lives in sqlite (parent card) and why `flush()` exists. ## Why the WAL checkpoint is a second connection `Store` owns its `Connection` and does not lend it out, and `src/store.rs` is explicitly out of this card's scope. A checkpoint is a property of the *database*, not of one connection, so `checkpoint_wal()` opens a short-lived second connection to `onionwire.db` and runs `PRAGMA wal_checkpoint(TRUNCATE)`. It needs no passphrase (it moves committed pages; it does not decrypt them), it is best-effort (a failure is logged, never fatal — WAL replay on open recovers anything committed), and it is covered by an offline test against a real WAL: `src/node.rs::lifecycle_tests::checkpoint_wal_truncates_a_live_wal`. ⚠️ **Forward-looking caveat — SQLCipher (#43/PR merged on `main` before this branch's base)**: on an encrypted store the key lives only inside `Store`, so a second plain connection cannot read the file at all. The helper detects that (`SQLITE_NOTADB` → "store is SQLCipher-encrypted — skipped") instead of reporting a bogus error, and nothing is lost — sqlite folds the WAL into the db when the last connection closes — but the explicit truncation has to move inside `Store` to happen there. Follow-up card **t_65c73d5a** filed for the store owner (`Store::checkpoint_wal()`), rather than reaching into a file this card forbids. ## Base branch Rebased onto **`main` @ `c39259b`** (the parent outbox PR #45 is merged, and this branch now carries the keystore `WireViewModel` from `main`, not the older one). Diff against `main` is exactly 6 files / 834 insertions: ``` 38fde75 feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state c068e29 feat(android): stop the node when the UI goes away 48c06df docs(sdk): Wire::shutdown doc said the second call returns Ok; it returns Stopped ``` Child cards stack here: `t_5bf32cd3` (foreground service) and `t_f46a9863` (Android outbox UI — it wants `Wire.flush()` / `FlushOutcome`). ## The bug the live test caught (read this one) The first `tor_state()` implementation projected Arti's raw combined status. `tests/tor_lifecycle.rs` — run for real against the Tor network, not just `--ignored` — failed with: ``` assertion `left == right` failed: start returns once the onion service is published left: Bootstrapping right: Published ``` Two distinct reasons, both device-visible: 1. `wait_until_published` accepts *either* a ready status **or** a successful probe of our own onion — that mismatch is the whole reason the 360s publish wait exists. Arti's combined status can sit at `Bootstrapping` for minutes after the descriptor is already downloadable, so a node friends could reach reported "still starting". 2. A freshly launched service reports `Shutdown` *before* its publish reactor starts (visible in the log: `Shutdown` for ~4s, then `Bootstrapping`, then `probe ok`). Projecting that to `Stopped` would make every unlock briefly look like a dead node — the worst possible answer from a lifecycle API. Fix: `Node` keeps an `onion_reachable` flag (`AtomicBool`) set when the publish bar is crossed in `start`/`rotate` and cleared when `rotate` hard-cuts the old service. `tor_state_of(state, stopped, reachable)` then mirrors `hs_is_ready` exactly: `Running` → `Published`, `DegradedReachable` → `DegradedReachable`, `Broken`/`Shutdown` on a live node → `Bootstrapping` (transient, not terminal), `Bootstrapping`/`DegradedUnreachable` + reachable → `Published`, and only the explicit stop flag (or a stopped service) yields `Stopped`. Covered by `tests/hs.rs::reachable_statuses_report_published_while_arti_says_bootstrapping` and `tor_state_maps_every_arti_status`. ## Verification (real output, head `48c06df`, rebased onto `main@c39259b`) ``` $ cargo test --locked Running unittests src/lib.rs / src/main.rs + tests/{app_sig,backup,dispatch,file,hs,outbox, pay,profile,protocol,qr,ratelimit,rotate,rotate_hs,sanitize,send,store,tor_hs,tor_lifecycle, tui_chrome,tui_frames,tui_spec,two_node,wallet,wipe,zeroize}.rs + Doc-tests -> 28 suites, 217 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out (the 4 ignored are the live-Tor suites: tor_hs, two_node, rotate_hs, tor_lifecycle) cargo test exit=0 $ cargo clippy --locked --all-targets -- -D warnings Finished `dev` profile [unoptimized + debuginfo] target(s) in 52.31s # clean clippy exit=0 $ cd crates/onionwire-sdk && cargo test tests::tor_state_of_a_stopped_handle_is_stopped ... ok tests::calls_after_shutdown_are_typed_errors_not_panics ... ok tests::tor_state_maps_every_core_state ... ok test result: ok. 3 passed # + tests/init_provider.rs 1 passed, tests/provider_resolution.rs 1 passed $ cargo test --locked --test tor_lifecycle -- --ignored --nocapture # live Tor network […]4ad.onion hs status: Bootstrapping # descriptor upload in flight, real Arti 2026-09-12T19:34:46Z INFO tor_hsservice::publish::reactor: reuploading descriptor in 1h 19m … test shutdown_stops_the_node_and_later_calls_are_typed_errors ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 25.28s $ cd android && CARGO_TARGET_DIR=… ./gradlew --no-daemon :app:assembleDebug > Task :sdk:mergeDebugNativeLibs > Task :app:stripDebugDebugSymbols Unable to strip the following libraries, packaging them as they are: libonionwire_sdk.so. > Task :app:compileDebugKotlin > Task :app:assembleDebug BUILD SUCCESSFUL in 4m 47s 61 actionable tasks: 15 executed, 46 up-to-date ``` Artifact (throwaway debug build, but it proves the toolchain and the regenerated bindings): ``` -rw-r--r-- 47012672 android/app/build/outputs/apk/debug/app-debug.apk sha256 d84cf7693ef0dab66e4570f2994ad86adf7fc977c1ac7d809da37614bd570891 18552536 classes.dex 34450376 lib/arm64-v8a/libonionwire_sdk.so = sha256 96234203d86ab2f43a2a78d65f88ab1c984c75673bfa78fb58918cdfb9953698 (byte-identical in size to the built aarch64-linux-android/release/libonionwire_sdk.so) ``` Generated Kotlin surface actually compiled into the AAR (`android/sdk/build/generated/uniffi/uniffi/onionwire_sdk/onionwire_sdk.kt`): ``` 1335: suspend fun `flush`(): FlushOutcome 1407: fun `torState`(): TorState 2189:enum class TorState { BOOTSTRAPPING, PUBLISHED, DEGRADED_REACHABLE, STOPPED } 2252: class Stopped(message: String) : WireException(message) ``` CI: **green** on `48c06df2cff7a265cce2dcabdd33d878b9857f41` — https://forgejo.siriusdevops.com/sirius/onionwire/actions/runs/174 (`ci / test`, pull_request, `cargo test --locked` + `cargo clippy --locked --all-targets -- -D warnings` inside the rust container on the arm64 Pi runner). ## Tests Offline (runs in CI / `cargo test`): * `tests/hs.rs` — `tor_state_maps_every_arti_status`, `stopped_outranks_whatever_arti_reports`, `ready_states_are_the_published_ones`. * `src/node.rs` — `checkpoint_wal_truncates_a_live_wal`, `checkpoint_wal_is_a_no_op_without_a_database`. * `crates/onionwire-sdk/src/lib.rs` — `tor_state_of_a_stopped_handle_is_stopped`, `calls_after_shutdown_are_typed_errors_not_panics`, `tor_state_maps_every_core_state`. Live Tor (`#[ignore]`, same convention as `tests/tor_hs.rs`): * `tests/tor_lifecycle.rs` — starts a node, asserts `Published`, flushes an empty outbox, shuts down, asserts `Stopped`, asserts the second `shutdown()` and a post-shutdown `flush()` / `send()` / `rotate()` all return errors instead of panicking. ## Naming decisions (as requested) * `Wire.shutdown()` / `Node::shutdown()` — not `stop()`/`close()`: it is a lifecycle transition, and `Stopped` is already the terminal state name. * `Wire.flush()` / `Node::flush()` — same word the TUI/card uses; returns `FlushOutcome { attempted, delivered, remaining }`. * `Wire.tor_state()` / `Node::tor_state()` — sync, read-only, no I/O. ## Not in this PR * The `README.md` wording is deferred (PR #38 owns the file) — see below. * `crates/onionwire-sdk/README.md` still says "No outbox, no spool in v1" and its "Locked protocol facts" table predates the outbox. Both are outside this card's allowed files; suggesting it here rather than silently editing. * `src/tui.rs` / `docs/TUI.md` (PR #27) untouched. * Side effect worth noting: `crates/onionwire-sdk` **did not compile on the base** — `Node::send` returns `Result<OutboxStatus, String>` after #45 while the SDK still mapped it to `Result<(), String>`, so `cargo build --release --lib` failed with E0308. CI's path allowlist excludes `crates/**` from the Rust job, which is why #45's `cargo test` run stayed green. Fixed here. ## README (deferred) Exact wording to apply to `README.md` after #38 lands — a lifecycle paragraph for the Android/SDK section: > #### Node lifecycle (Android SDK) > > A node is explicit about starting and stopping: > > ```kotlin > val wire = openWire(filesDir.absolutePath + "/onionwire", passphrase) // published before it returns > wire.flush() // deliver everything queued now (bounded, 30s) > wire.torState() // BOOTSTRAPPING | PUBLISHED | DEGRADED_REACHABLE | STOPPED > wire.shutdown() // drain, stop the onion service, checkpoint, release Tor > ``` > > `shutdown()` is safe to call twice — the second call throws the typed > `WireException.Stopped` rather than panicking — and every call after it fails > the same way instead of touching a dead Tor client. Call it from your > `ViewModel.onCleared()` / service `onDestroy()`: the node must not outlive the > UI. Android can kill your process at any time without running either, which is > why queued chat sends live in sqlite and not in memory.
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 3m21s
ad59a171b3
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
  is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
  messages row, under that row's existing AEAD + AAD), append_message_id(),
  queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
  Err on transport failure; protocol errors still fail immediately and are
  never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
  was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
  add the seizure/cadence delta to the threat model.

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the
Kotlin reference left Arti's client, the hosted v3 onion service, the outbox
retry worker and the sqlite connection alive, and there was no way to ask where
the onion service was. On Android the process is killed without warning by Doze
and the background-process killer, so "drop everything when the process dies" is
not a lifecycle.

Core (`src/node.rs`, `src/hs.rs`):

* `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the
  rendezvous task is aborted and the RunningOnionService dropped), abort the
  retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is
  swapped first, so a racing second call is a no-op.
* `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one
  delivery attempt for every queued outbox row, ignoring backoff, then a WAL
  checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s
  and the caller is a UI thread. A timeout leaves rows in `sending`;
  `Outbox::reset_stale` requeues them on the next unlock, same as a process that
  died mid-attempt.
* `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` /
  `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped,
  reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving
  readiness.
* Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`,
  `flush`) fails with a typed error after the node stops, rather than dialing a
  dead client.
* `checkpoint_wal` reaches the database through a short-lived second connection:
  `Store` owns the write connection and does not lend it out, and a checkpoint is
  a property of the database, not of one connection. Best effort — WAL replay on
  open recovers anything committed.

The `WorkerHandle` moved into a `Mutex<Option<...>>` so the teardown can *abort*
the retry worker instead of only dropping it when the whole `Node` dies.

SDK (`crates/onionwire-sdk/src/lib.rs`):

* `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`.
  `Wire` now holds `Mutex<Option<Arc<Node>>>`, so teardown drops the last
  reference to the Tor client and the store instead of keeping them alive behind
  a JNI handle.
* `WireError::Stopped` — a second flat variant, so "you must unlock again" is a
  typed `WireException.Stopped` in Kotlin, not a string match on `Failed`.
* No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports
  `Stopped`, which is the correct recovery (unlock again).
* Fixes the crate not compiling on this base at all: `Node::send` has returned
  `Result<OutboxStatus, String>` since the outbox landed, and the SDK still
  mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes
  `crates/**` from the Rust job, which is why it stayed green.

The live Tor test found a real bug in the first version of `tor_state`: Arti's
combined status is still `Bootstrapping` after a *successful* probe of our own
onion (that mismatch is what the 360s publish wait exists for), and a freshly
launched service reports `Shutdown` before its publish reactor starts — so a
node that was live and reachable reported `Bootstrapping`, and briefly
`Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set
when the publish bar is crossed and cleared when `rotate` hard-cuts the service,
and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather
than terminal.
feat(android): stop the node when the UI goes away
All checks were successful
ci / test (pull_request) Successful in 3m38s
3d41ffceb3
`WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all,
so neither the user pressing Lock nor the Activity finishing stopped anything:
Arti kept its client and the hosted onion service, the outbox worker kept
dialing, and the sqlite connection stayed open behind the JNI handle.

Both paths now go through `stopNode(Wire)`:

1. `flush()` — one last bounded drain, so a queued message gets its chance
   before the process may lose its socket.
2. `shutdown()` — drain again with a shorter budget, stop the onion service,
   abort the retry worker, checkpoint the WAL, and take the node handle out of
   the `Wire` (which is what releases the last Arc to the Tor client and the
   store).

Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`)
because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors
are deliberately swallowed there: the UI is gone, and the SDK reports a second
teardown as the typed `WireException.Stopped` rather than a panic.

`unlock()` joins any in-flight teardown before opening again. The old node holds
the sqlite file and Arti's state lock until its teardown returns, and racing it
makes the next `openWire` fail.

A process killed outright (Doze, background-process killer, force-stop) still
never runs any of this — that is what the sqlite outbox and the new `flush()`
are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from
the ViewModel to the service.
sirius force-pushed feat/tor-lifecycle from 3d41ffceb3
All checks were successful
ci / test (pull_request) Successful in 3m38s
to b053bed702
All checks were successful
ci / test (pull_request) Successful in 3m15s
2026-09-12 18:35:59 +00:00
Compare
sirius force-pushed feat/tor-lifecycle from b053bed702
All checks were successful
ci / test (pull_request) Successful in 3m15s
to 48c06df2cf
All checks were successful
ci / test (pull_request) Successful in 4m22s
2026-09-12 19:31:28 +00:00
Compare
sirius changed target branch from feat/local-outbox to main 2026-09-12 19:31:59 +00:00
sirius merged commit 02b531625f into main 2026-09-12 20:58:31 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sirius/onionwire!49
No description provided.