From 745d2a86e01c0c9781793d98c881858e9136f091 Mon Sep 17 00:00:00 2001 From: Blake McAnally Date: Thu, 12 Nov 2026 14:31:49 -0600 Subject: [PATCH] fix(cli): treat a retried sidebar write the relay already stored as success (#9202) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #9191. It addresses the review findings that came in as that PR merged. ## Summary **A retried write was reported as a conflict.** This was found by the Codex security review on #9191 (LOW). - `BuzzClient::submit_event` can resend the same signed event after an ambiguous attempt, for example a timeout after the relay stored it. - The relay answers that resend `accepted: true, message: "duplicate:"`. `publish` turned any `duplicate:` into exit 5 with "a newer update won; run the command again". - If you ran `buzz sidebar sections create` again, you got a second section. On a `duplicate:` reply, `publish` now re-reads the head from the writer (`consistency: strong`). It reports success only when the head is the event it signed. The check is safe because `replace_parameterized_event` returns `was_inserted = false` for both an exact-id duplicate and a stale (dominated) write. Only a stored event can be the head with our id, so a dominated write still exits 5. **Unknown keys are dropped on decode.** This was raised by joahg on #9191. The module docs now state the limitation and why it is safe: - Buzz Desktop (`block/buzz-app`, `validate_sidebar_payload`) refuses to sign a document with unknown keys, so a new field needs a new `meta.v`. - `decode` refuses an unknown `meta.v`. The commands then neither read nor overwrite that head. ## Not changed joahg also noted the lost-update window between the head read and the submit. That window is documented in `crates/buzz-cli/README.md` (from #9191). A kind:30078 replaceable event has no compare-and-set on the relay, so the CLI cannot detect the case. A test would only check the fake relay's replace rules. ## Testing - `cargo test -p buzz-cli`: 665 pass. `cargo clippy -p buzz-cli --all-targets -D warnings` and `cargo fmt --check` are clean. - New test: `a_retry_of_a_stored_write_is_success`. The fake relay stores the event and answers `duplicate:`. The test fails without the fix (`Conflict("a newer sidebar sections update won; run the command again")`). - `a_dominated_write_is_a_conflict` now seeds a newer head under the caller's own key. Before, every conflict test had an empty own head, so a looser check (`Some(_)`) still passed. The test now fails under that change. - An agent review ran. It found that gap in the dominated-write test, which is now fixed. Its remaining notes are optional. ### Manual test steps The retry path needs a lost relay response, so you cannot easily trigger it by hand. These steps check that normal writes did not change: 1. Run `cargo build -p buzz-cli`. Then set `BUZZ_RELAY_URL` and either pair with Buzz Desktop (`buzz auth desktop pair`) or set `BUZZ_PRIVATE_KEY`. 2. Run `buzz sidebar sections list` and save the output. 3. Run `buzz sidebar sections create --name "Retry test"`. Expected: `"accepted": true`, a non-null `event_id`, and a `section_id`. 4. Run `buzz sidebar sections delete --section "Retry test"`. Then run `list` again. Expected: the same output as step 2. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Blake McAnally Co-authored-by: Claude Opus 5.5 --- crates/buzz-cli/src/commands/sidebar.rs | 25 +++++++ crates/buzz-cli/src/commands/sidebar_doc.rs | 6 ++ crates/buzz-cli/src/commands/sidebar_sync.rs | 74 +++++++++++++------- 3 files changed, 78 insertions(+), 27 deletions(-) diff --git a/crates/buzz-cli/src/commands/sidebar.rs b/crates/buzz-cli/src/commands/sidebar.rs index 77c2620914..708bf8a758 100644 --- a/crates/buzz-cli/src/commands/sidebar.rs +++ b/crates/buzz-cli/src/commands/sidebar.rs @@ -456,6 +456,12 @@ mod tests { #[tokio::test] async fn a_dominated_write_is_a_conflict() { let (client, relay) = setup().await; + seed_at( + &client, + &relay, + &doc_with_sections(&["Theirs"]), + now().as_secs() + 3_600, + ); relay.lock().unwrap().duplicate = true; let err = run( SidebarSectionsCmd::Create { @@ -468,4 +474,23 @@ mod tests { .unwrap_err(); assert!(matches!(err, CliError::Conflict(_)), "{err:?}"); } + + #[tokio::test] + async fn a_retry_of_a_stored_write_is_success() { + let (client, relay) = setup().await; + relay.lock().unwrap().stored_duplicate = true; + let out = run( + SidebarSectionsCmd::Create { + name: "Once".into(), + icon: None, + }, + &client, + ) + .await + .unwrap(); + let (event, _) = published(&client, &relay); + assert_eq!(out["event_id"], json!(event.id.to_hex())); + assert_eq!(out["message"], json!("")); + assert_eq!(published_count(&relay), 1); + } } diff --git a/crates/buzz-cli/src/commands/sidebar_doc.rs b/crates/buzz-cli/src/commands/sidebar_doc.rs index 16c3a40e73..75bf3d8977 100644 --- a/crates/buzz-cli/src/commands/sidebar_doc.rs +++ b/crates/buzz-cli/src/commands/sidebar_doc.rs @@ -6,6 +6,12 @@ //! last-writer-wins registers `[v, dev, value]` under `meta`, plus the //! projected legacy fields that meta-less clients (mobile) read and write. //! A [`Codec`] describes one document's shape, legacy import and projection. +//! +//! Like desktop, decoding drops any key or register its shape does not know, +//! and the republished snapshot omits it. Buzz Desktop (`block/buzz-app`, +//! `validate_sidebar_payload`) refuses to sign a document with unknown keys, +//! so a new field needs a new `meta.v`; [`decode`] refuses an unknown +//! `meta.v`, and the commands then neither read nor overwrite the head. use std::collections::BTreeMap; diff --git a/crates/buzz-cli/src/commands/sidebar_sync.rs b/crates/buzz-cli/src/commands/sidebar_sync.rs index 07544e2509..1a43885354 100644 --- a/crates/buzz-cli/src/commands/sidebar_sync.rs +++ b/crates/buzz-cli/src/commands/sidebar_sync.rs @@ -46,17 +46,10 @@ pub(crate) fn channel_ids(channels: &[String]) -> Result, CliError> .collect() } -/// The relay's current event for `lane` and this identity, decrypted and -/// passed to `decode` with the event's `created_at`. An absent head is -/// `doc: None`; an unreadable one is an error, never an empty document. The -/// read is pinned to the writer (`consistency: strong`): a write derives a -/// full snapshot from it, and a lagging replica would drop the caller's own -/// just-accepted edits. -pub(crate) async fn fetch_head( - client: &BuzzClient, - lane: Lane, - decode: impl FnOnce(&Value, u64) -> Option, -) -> Result, CliError> { +/// The relay's current verified `lane` event for this identity, read from the +/// writer. `None` when the relay holds none; an error when it returns only +/// events that are not yours or fail verification. +async fn head_event(client: &BuzzClient, lane: Lane) -> Result, CliError> { let me = client.public_key(); let filter = json!({ "kinds": [KIND_READ_STATE], @@ -82,19 +75,33 @@ pub(crate) async fn fetch_head( .cmp(&a.created_at) .then_with(|| a.id.to_hex().cmp(&b.id.to_hex())) }); - let Some(event) = head else { - if returned > 0 { - return Err(CliError::Other(format!( - "the relay returned a {} event that is not yours or fails verification; refusing to overwrite it", - lane.label - ))); - } + if head.is_none() && returned > 0 { + return Err(CliError::Other(format!( + "the relay returned a {} event that is not yours or fails verification; refusing to overwrite it", + lane.label + ))); + } + Ok(head) +} + +/// The relay's current event for `lane` and this identity, decrypted and +/// passed to `decode` with the event's `created_at`. An absent head is +/// `doc: None`; an unreadable one is an error, never an empty document. The +/// read is pinned to the writer (`consistency: strong`): a write derives a +/// full snapshot from it, and a lagging replica would drop the caller's own +/// just-accepted edits. +pub(crate) async fn fetch_head( + client: &BuzzClient, + lane: Lane, + decode: impl FnOnce(&Value, u64) -> Option, +) -> Result, CliError> { + let Some(event) = head_event(client, lane).await? else { return Ok(Head { created_at: 0, doc: None, }); }; - + let me = client.public_key(); let unreadable = |detail: String| { CliError::Other(format!( "your {} event {} is unreadable ({detail}); refusing to read or overwrite it", @@ -120,7 +127,9 @@ pub(crate) async fn fetch_head( /// Encrypts `plaintext` to yourself and publishes it as the new head, one /// second after `head_created_at` at the earliest. A relay `duplicate:` reply -/// is a conflict. +/// is a conflict unless the head is this event: `submit_event` retries an +/// ambiguous attempt with the same signed event, which the relay then reports +/// as a duplicate of the copy it already stored. pub(crate) async fn publish( client: &BuzzClient, lane: Lane, @@ -150,13 +159,21 @@ pub(crate) async fn publish( let builder = EventBuilder::new(Kind::Custom(KIND_READ_STATE as u16), content) .tags([Tag::identifier(lane.d_tag), Tag::hashtag(lane.d_tag)]) .custom_created_at(Timestamp::from(created_at)); - let raw = client - .submit_event(client.sign_event(builder).await?) - .await?; - let normalized = parse_write_response( + let event = client.sign_event(builder).await?; + let event_id = event.id; + let raw = client.submit_event(event).await?; + let normalized = match parse_write_response( &raw, &format!("a newer {} update won; run the command again", lane.label), - )?; + ) { + Err(CliError::Conflict(conflict)) => match head_event(client, lane).await? { + Some(head) if head.id == event_id => { + json!({"event_id": event_id.to_hex(), "accepted": true, "message": ""}).to_string() + } + _ => return Err(CliError::Conflict(conflict)), + }, + other => other?, + }; serde_json::from_str(&normalized) .map_err(|e| CliError::Other(format!("relay response is not JSON: {e}"))) } @@ -223,6 +240,9 @@ pub(crate) mod test_support { pub struct Relay { pub events: Vec, pub duplicate: bool, + /// Store the event but answer `duplicate:`, as the relay answers a + /// retry of an attempt it already stored. + pub stored_duplicate: bool, /// Answer every query with all stored events, whoever authored them. pub leaky: bool, } @@ -262,8 +282,8 @@ pub(crate) mod test_support { post(|State(relay): State, body: Bytes| async move { let event: Value = serde_json::from_slice(&body).unwrap(); let mut relay = relay.lock().unwrap(); - let message = if relay.duplicate { - "duplicate: newer head" + let message = if relay.duplicate || relay.stored_duplicate { + "duplicate:" } else { "" };