notes: drop the busy-save retries on desktop and Android
Build Debug APK / build (push) Successful in 6m45s

save_body_with_retry and retryOnBusy re-ran a failed note save twice, two
seconds apart, because a save that read and then wrote lost to any sync commit
in between with SQLITE_BUSY_SNAPSHOT. Saves are writes now and queue for the
lock instead (ADR 0057), and a busy that still gets through has already waited
BUSY_TIMEOUT, so each save is one attempt. retryOnBusy also retried failures
that weren't busy at all. The save-failed copy no longer says it retried, and
the FFI error docs no longer cite retryOnBusy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 5.5 committed 2026-11-04 04:39:53 -08:00
1 parent 751802b2d7
commit ad15d5ef23
6 files changed
+28 -138

No files matched your search

-6
View File
@@ -573,12 +573,6 @@ wrote lost its snapshot to any commit in between (`SQLITE_BUSY_SNAPSHOT`, at onc
`BUSY_TIMEOUT` says). Writes now go through `write` and a `WriteTx`, which begin `IMMEDIATE`
and queue for the lock instead (ADR 0057). `stores::contention` logs every busy failure with
its extended code and call site, and any write transaction held past a second.
- **Retire the retries.** The desktop's `save_body_with_retry` in Notes and Android's
`retryOnBusy` were workarounds for the snapshot failure, which can't happen any more. A
busy that still gets through has already waited `BUSY_TIMEOUT` (5 s), so retrying it two
seconds later is not the fix either. `retryOnBusy` also retries *any* failure, and its doc
says it can't tell a busy database from other failures, which is stale:
`SyncError::Busy` carries `Recourse::RetryNow`.
- **The ~5 s stalls are unexplained.** Nested batches were ruled out on 2026-11-03 (and are
now caught by `contention`'s nesting check), so a stall means some writer held the lock
for 5 s. If one recurs, `contention`'s "held the write lock for …" warning names it.
@@ -3,7 +3,6 @@ package com.gregshuflin.synchronicity.notes
import android.util.Log
import com.gregshuflin.synchronicity.NativeLib
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import uniffi.synchronicity.DocumentAvailability
import uniffi.synchronicity.MathDialect
@@ -14,15 +13,6 @@ import uniffi.synchronicity.TextFormat
private const val TAG = "NotebookRepository"
// A note body save races the background sync scheduler writing to the same store.db from
// its own connection (see rust/lib/src/stores/mod.rs's BUSY_TIMEOUT doc comment), which can
// transiently outlast SQLite's own 5s busy_timeout. Mirrors the gpui desktop app's
// `save_body_with_retry` (rust/gui-app/src/agents/notes/mod.rs): autosave has no "save"
// button to retry from, so a transient lock should be retried quietly rather than crashing
// the app the instant one attempt outlasts the busy timeout.
internal const val SAVE_RETRIES = 2
internal const val SAVE_RETRY_DELAY_MS = 2000L
// One small function per notebook FFI call (mirrors NativeLib's own justification for the
// same suppression) — splitting the class wouldn't reduce real complexity, just spread the FFI
// surface across files.
@@ -154,11 +144,13 @@ class NotebookRepository {
NativeLib.ffi { notebook().createCollection(parentId, title) }
}
/**
* One attempt: the save is a store `write`, which waits its turn for the write lock rather than
* failing when a sync is writing at the same moment (ADR 0057).
*/
suspend fun updateNote(noteId: String, newTitle: String, newBody: String): Result<Unit> =
withContext(Dispatchers.IO) {
retryOnBusy(onRetry = { Log.w(TAG, "Note save failed — retrying", it) }) {
NativeLib.ffi { notebook().updateNote(noteId, newTitle, newBody) }
}
NativeLib.ffi { notebook().updateNote(noteId, newTitle, newBody) }
}
suspend fun renameItem(id: String, newTitle: String): Result<Unit> =
@@ -168,29 +160,6 @@ class NotebookRepository {
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().deleteItem(id) } }
}
/**
* Runs [block], retrying a failure up to [SAVE_RETRIES] times (waiting [SAVE_RETRY_DELAY_MS]
* between attempts, and telling [onRetry] why) before returning the last one. See the comment on
* [SAVE_RETRIES] for why this exists.
*
* This retries *any* failure, not just the transient lock contention it exists for. Now that `ffi {
* }` wraps unexpected exceptions into `SyncException.General`, a narrower filter would have to
* match on message text to tell the two apart, which is worse than occasionally spending two extra
* delays on a failure that was never going to succeed.
*/
internal suspend fun <T> retryOnBusy(
onRetry: (Throwable?) -> Unit,
block: () -> Result<T>,
): Result<T> {
repeat(SAVE_RETRIES) {
val attempt = block()
if (attempt.isSuccess) return attempt
onRetry(attempt.exceptionOrNull())
delay(SAVE_RETRY_DELAY_MS)
}
return block()
}
/**
* The Rust tree as the sidebar's [NoteTreeItem]s. Availability is not loaded on demand, unlike the
* body: the tree marks every row at once, and the native side already answered per node while it
@@ -1,53 +0,0 @@
package com.gregshuflin.synchronicity.notes
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.currentTime
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* A note save that loses a race for the store's lock is retried quietly, since autosave has no
* button to retry from. Each case reports what the caller sees, how many attempts it took, and how
* long it waited (virtual time, so the test doesn't).
*/
@OptIn(ExperimentalCoroutinesApi::class)
class RetryOnBusyTest {
private data class Outcome(val result: Result<String>, val attempts: Int, val waitedMs: Long)
/** Run [retryOnBusy] over attempts that fail until [failures] of them have. */
private suspend fun TestScope.saveFailing(failures: Int): Outcome {
var attempts = 0
val result =
retryOnBusy(onRetry = {}) {
attempts++
if (attempts <= failures) Result.failure(IllegalStateException("busy $attempts"))
else Result.success("saved")
}
return Outcome(result, attempts, currentTime)
}
@Test
fun `a save that succeeds is not retried`() = runTest {
assertEquals(Outcome(Result.success("saved"), 1, 0), saveFailing(failures = 0))
}
@Test
fun `a save that fails once succeeds after one wait`() = runTest {
assertEquals(
Outcome(Result.success("saved"), 2, SAVE_RETRY_DELAY_MS),
saveFailing(failures = 1),
)
}
/** The last failure is the one returned, so the caller reports what is true now. */
@Test
fun `a save that never succeeds gives up with the last failure`() = runTest {
val outcome = saveFailing(failures = Int.MAX_VALUE)
assertEquals(SAVE_RETRIES + 1, outcome.attempts)
assertEquals(SAVE_RETRIES * SAVE_RETRY_DELAY_MS, outcome.waitedMs)
assertEquals("busy ${SAVE_RETRIES + 1}", outcome.result.exceptionOrNull()?.message)
}
}
+14 -31
View File
@@ -139,17 +139,6 @@ const MATH_CACHE_CAPACITY: NonZeroUsize = NonZeroUsize::new(128).unwrap();
/// auto-saved. Switching notes/notebooks flushes any pending edit immediately.
const SAVE_DEBOUNCE: Duration = Duration::from_millis(600);
/// How many times to retry a save that hits `SQLITE_BUSY` (e.g. the
/// background sync scheduler mid-tick, see `scheduler_driver.rs`, writing to
/// the same `store.db` at the same moment) before giving up and surfacing an
/// error. Autosave has no "save" button for the user to retry from, so a
/// transient lock — which resolves itself as soon as whatever else is
/// writing finishes — should be retried quietly rather than alarming the
/// user the instant a single attempt outlasts SQLite's own 5s
/// `BUSY_TIMEOUT` (`stores::mod::BUSY_TIMEOUT`).
const SAVE_RETRIES: u32 = 2;
const SAVE_RETRY_DELAY: Duration = Duration::from_secs(2);
/// Which top-level content the Notes agent shows — the notebook/note browser
/// (the normal state) or its own settings screen, reached via the gear icon
/// in [`NotesView::render_header`]. Distinct from [`NotesViewMode`], which
@@ -864,7 +853,7 @@ impl NotesView {
return;
};
let save_id = note_id.clone();
let result = save_body_with_retry(cx, &store, node, &note_id, &text).await;
let result = save_body_in_background(cx, &store, node, &note_id, &text).await;
this.update(cx, |this, cx| {
match result {
Ok(modified) => {
@@ -910,7 +899,7 @@ impl NotesView {
let store = Arc::clone(&self.store);
let node = self.node;
cx.spawn(async move |this, cx| {
let result = save_body_with_retry(cx, &store, node, &note_id, &text).await;
let result = save_body_in_background(cx, &store, node, &note_id, &text).await;
this.update(cx, |this, cx| {
match result {
Ok(_) => {
@@ -2569,30 +2558,24 @@ fn save_body(
Ok(doc.modified_at)
}
/// [`save_body`], retried [`SAVE_RETRIES`] times (waiting [`SAVE_RETRY_DELAY`]
/// between attempts) before giving up. Shared by [`NotesView::schedule_save`]
/// and [`NotesView::flush_save`].
async fn save_body_with_retry(
/// [`save_body`] on the background executor. Shared by
/// [`NotesView::schedule_save`] and [`NotesView::flush_save`].
///
/// One attempt: a save is a `write`, which waits its turn for the store's write
/// lock rather than failing when a sync is writing at the same moment (ADR
/// 0057). A save that fails anyway has already waited out `BUSY_TIMEOUT`, so
/// waiting again here wouldn't help.
async fn save_body_in_background(
cx: &mut gpui::AsyncApp,
store: &Arc<Store>,
node: NodePubkey,
note_id: &DocumentID,
text: &str,
) -> Result<Timestamp, String> {
let mut last_err = String::new();
for attempt in 0..=SAVE_RETRIES {
if attempt > 0 {
cx.background_executor().timer(SAVE_RETRY_DELAY).await;
}
let store = Arc::clone(store);
let node_id = note_id.clone();
let text = text.to_string();
match cx.background_spawn(async move { save_body(&store, node, &node_id, &text) }).await {
Ok(modified) => return Ok(modified),
Err(e) => last_err = e,
}
}
Err(last_err)
let store = Arc::clone(store);
let note_id = note_id.clone();
let text = text.to_string();
cx.background_spawn(async move { save_body(&store, node, &note_id, &text) }).await
}
// ── Typst diagnostics ────────────────────────────────────────────────────────
+5 -8
View File
@@ -121,17 +121,14 @@ pub fn create_notebook_failed(reason: impl Display) -> String {
format!("Failed to create notebook: {reason}")
}
/// A body save that failed even after its retries. `will_retry` — whether
/// the editor is still open to try again on the next keystroke, as
/// against a final save on the way out of the note.
/// A body save that failed. `will_retry` — whether the editor is still open
/// to try again on the next keystroke, as against a final save on the way out
/// of the note.
pub fn save_failed(reason: impl Display, will_retry: bool) -> String {
if will_retry {
format!(
"Couldn't save this note after retrying ({reason}) — it'll try again as you \
keep editing."
)
format!("Couldn't save this note ({reason}) — it'll try again as you keep editing.")
} else {
format!("Couldn't save this note after retrying ({reason}).")
format!("Couldn't save this note ({reason}).")
}
}
+4 -4
View File
@@ -95,8 +95,8 @@ impl SyncError {
// the thing destroying the information. See docs/adr/0023.
//
// Two rules of thumb:
// - `Busy` (SQLite lock contention) is retryable *now* — it is the reason Android's
// NotebookRepository::retryOnBusy exists, and it can finally be told apart from a bug.
// - `Busy` (SQLite lock contention) is retryable *now*: the person can try again at once,
// and it can be told apart from a bug.
// - transport failures (connect/read/write/stream-closed) are `Offline`, retryable
// *later*: an immediate retry is guaranteed to fail, so frontends should queue.
@@ -128,8 +128,8 @@ sync_error_from_store!(crate::stores::document_sync_override::DocumentSyncOverri
///
/// Delegates to the wrapped error's own conversion rather than flattening
/// everything to `Internal`: `Busy` (SQLite lock contention) is retryable
/// *now* and is what Android's `retryOnBusy` keys on, so losing it inside the
/// umbrella would turn a routine retry into a reported bug.
/// *now*, so losing it inside the umbrella would turn contention the person
/// can simply retry into a reported bug.
impl From<StoreError> for SyncError {
fn from(e: StoreError) -> Self {
match e {