@@ -194,9 +194,24 @@ impl SecretStore {
194194 }
195195 }
196196
197- /// Atomically load the blob, apply `f` to the map, write back, and update
198- /// the cache — all while holding the cache mutex. This serializes concurrent
199- /// writes so no caller can observe a partial update.
197+ /// Atomically load the blob, apply `f` to a candidate map, write back if
198+ /// changed, and only then advance the cache — all while holding the cache
199+ /// mutex. This serializes concurrent writes so no caller can observe a
200+ /// partial update.
201+ ///
202+ /// **Idempotent**: when `f` leaves the candidate equal to the current cached
203+ /// map, `write_blob_raw` is skipped entirely. On macOS the legacy
204+ /// `SecKeychain` API treats a write as a distinct ACL operation from the
205+ /// "Always Allow"-ed read, so skipping no-op writes eliminates the keychain
206+ /// prompt that fires when saving an agent whose model changed but whose key
207+ /// did not.
208+ ///
209+ /// **Copy-on-write**: the candidate `next` is a separate allocation from the
210+ /// cached `current`. The cache is only replaced with `next` after
211+ /// `write_blob_raw` succeeds. On write failure the cache stays at the last
212+ /// known durable state — a transient ACL denial or keychain outage cannot
213+ /// advance the cache past durably-written storage and silently drop a later
214+ /// write attempt.
200215 ///
201216 /// Deadlock-free: `read_blob_raw` and `write_blob_raw` do not acquire the
202217 /// cache mutex. `load_blob` does acquire it, but `mutate_blob` does not call
@@ -222,14 +237,29 @@ impl SecretStore {
222237 } ) ;
223238 }
224239
225- let map = guard. as_mut ( ) . expect ( "just initialized above" ) ;
226- f ( map) ;
240+ let current = guard. as_ref ( ) . expect ( "just initialized above" ) ;
241+
242+ // Build the candidate state in a separate allocation so that a write
243+ // failure below cannot leave the cache ahead of durable storage.
244+ // `HashMap` `PartialEq` compares by content (key-value pairs), not
245+ // iteration order, so the equality check is order-safe.
246+ let mut next = current. clone ( ) ;
247+ f ( & mut next) ;
248+
249+ // Skip the keychain write when the candidate equals the current durable
250+ // state — the cache already mirrors storage and no I/O is needed.
251+ if next == * current {
252+ return Ok ( ( ) ) ;
253+ }
227254
228255 // Write to keyring while still holding the lock.
229- let json = serde_json:: to_string ( map ) . map_err ( |e| format ! ( "blob serialize: {e}" ) ) ?;
256+ let json = serde_json:: to_string ( & next ) . map_err ( |e| format ! ( "blob serialize: {e}" ) ) ?;
230257 self . write_blob_raw ( json. as_bytes ( ) ) ?;
231258
232- // Cache is already up to date (we mutated it in place).
259+ // Advance the cache only after the durable write succeeds. On failure
260+ // the early return above means we never reach this line, so the cache
261+ // remains at the last known durable state.
262+ * guard = Some ( next) ;
233263 Ok ( ( ) )
234264 }
235265
@@ -514,6 +544,74 @@ mod tests {
514544 ) ;
515545 }
516546
547+ #[ test]
548+ fn mutate_blob_skips_write_when_map_unchanged ( ) {
549+ // The idempotent-write guarantee: when the closure leaves the map
550+ // identical to its pre-call state, `write_blob_raw` must NOT be
551+ // invoked. On an unsigned CI build (no keychain entitlement) any real
552+ // write would return an error, so a successful `Ok(())` here proves
553+ // the skip path fired. The service name is unique so test isolation is
554+ // guaranteed even if the test runs locally on a machine with a keychain.
555+ let mut map = HashMap :: new ( ) ;
556+ map. insert ( "identity" . to_string ( ) , "nsec1test" . to_string ( ) ) ;
557+ let store = SecretStore :: with_cache ( "buzz-test-idempotent-skip" , Some ( map) ) ;
558+
559+ // Re-storing the exact same value must succeed without touching the
560+ // keychain (which would fail on unsigned CI).
561+ let result = store. store ( "identity" , "nsec1test" ) ;
562+ assert ! (
563+ result. is_ok( ) ,
564+ "no-op store must not reach write_blob_raw: {result:?}"
565+ ) ;
566+ // A genuinely new key DOES change the map — this branch requires a
567+ // real keychain and is therefore left to the #[ignore] integration
568+ // tests; here we only verify the skip path.
569+ }
570+
571+ #[ test]
572+ fn mutate_blob_does_not_advance_cache_on_write_failure ( ) {
573+ // Copy-on-write safety: if `write_blob_raw` fails (denied prompt,
574+ // transient outage, ACL rejection), the cache must stay at the last
575+ // known durable state. A subsequent `store()` for the same key/value
576+ // must NOT be skipped as a no-op — the equality check must compare
577+ // against the durable cache, not an unpersisted candidate.
578+ //
579+ // On unsigned CI builds the keychain is unreachable, so any `store()`
580+ // for a key not already in the warm cache will call `write_blob_raw`
581+ // and receive an error. We verify that after the error:
582+ // 1. The cache is not advanced (the previously cached key is intact).
583+ // 2. The failed key is not present (the dirty candidate was discarded).
584+ let mut map = HashMap :: new ( ) ;
585+ map. insert ( "existing" . to_string ( ) , "durable_val" . to_string ( ) ) ;
586+ let store = SecretStore :: with_cache ( "buzz-test-cow-write-fail" , Some ( map) ) ;
587+
588+ // Attempt to add a new key — on unsigned CI this will try write_blob_raw
589+ // and fail; with copy-on-write the cache must remain at {existing}.
590+ let result = store. store ( "new_key" , "new_val" ) ;
591+
592+ if result. is_err ( ) {
593+ // Write failed (expected on unsigned CI): confirm cache was not
594+ // advanced — the existing key is still intact and the new key
595+ // was never committed to the in-memory state.
596+ assert_eq ! (
597+ store. load( "existing" ) . unwrap( ) ,
598+ Some ( "durable_val" . to_string( ) ) ,
599+ "cache must remain at last durable state after write failure"
600+ ) ;
601+ // load("new_key") goes through the unchanged cache (no entry),
602+ // then attempts migrate_legacy_key which also fails on unsigned CI,
603+ // returning either Ok(None) or Err — either is correct since the
604+ // key was never durably stored.
605+ let after = store. load ( "new_key" ) ;
606+ assert ! (
607+ matches!( after, Ok ( None ) | Err ( _) ) ,
608+ "a key whose write failed must not be visible via load: {after:?}"
609+ ) ;
610+ }
611+ // If result.is_ok() the test ran on a machine with a real keychain and
612+ // the write succeeded — no assertion needed for the failure path.
613+ }
614+
517615 #[ test]
518616 fn availability_error_discriminator ( ) {
519617 assert ! ( is_keyring_availability_error( "dbus connection failed" ) ) ;
0 commit comments