From 5f96c738d8db66f3f770dcb29671dd7395b19882 Mon Sep 17 00:00:00 2001 From: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 Date: Mon, 6 Jul 2026 17:28:46 -0400 Subject: [PATCH] fix(archive): close TOCTOU race on shared owner_p row with atomic DB merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two concurrent seed hooks (observer 24200 + metric 44200) each fire on first internal-build run with no prior owner_p row. The old TS-side read-then-write merge raced: each hook read [] before the other had written, so last writer clobbered the first kind. Add store::merge_owner_p_kinds: reads existing kinds JSON, unions in new_kind, and writes back under a single SQLite unchecked_transaction. Concurrent callers serialize on the SQLite write lock — last writer always reads the first writer's committed row. Add merge_save_subscription_kinds Tauri command in archive/mod.rs (same module as the other subscription commands; registered in lib.rs). Both seed hooks and their deps interfaces now call this single command with just their own kind, replacing the list+merge+create pattern. tauriArchive.ts gains a mergeSaveSubscriptionKinds() binding. Tests added: - store.rs: create-when-none, adds-kind-to-existing, idempotent, concurrent-interleave (observer writes first, metric second, both kinds survive) - useAgentMetricArchiveSeed.test.mjs: updated to new deps interface, adds test_concurrent_seeds_both_kinds_survive (Promise.all interleave) - useObserverArchiveSeed.test.mjs: symmetric update to new interface File-size overrides bumped: archive/mod.rs +30 (command), store.rs +110 (new fn + 4 tests — first override for store.rs). Co-authored-by: Will Pfleger Signed-off-by: Will Pfleger --- desktop/scripts/check-file-sizes.mjs | 9 +- desktop/src-tauri/src/archive/mod.rs | 29 ++++ desktop/src-tauri/src/archive/store.rs | 134 +++++++++++++++ desktop/src-tauri/src/lib.rs | 1 + .../useAgentMetricArchiveSeed.test.mjs | 157 ++++++++++-------- .../useAgentMetricArchiveSeed.ts | 40 +---- .../useObserverArchiveSeed.test.mjs | 47 +++--- .../local-archive/useObserverArchiveSeed.ts | 45 ++--- desktop/src/shared/api/tauriArchive.ts | 16 ++ 9 files changed, 322 insertions(+), 156 deletions(-) diff --git a/desktop/scripts/check-file-sizes.mjs b/desktop/scripts/check-file-sizes.mjs index e9ba37875..d0aeb3d35 100644 --- a/desktop/scripts/check-file-sizes.mjs +++ b/desktop/scripts/check-file-sizes.mjs @@ -73,7 +73,14 @@ const overrides = new Map([ // decrypt-success plaintext storage, decrypt-fail-closed, 24200 still // ephemeral) + run_batch_sync_with_keys helper (~175 lines). Same test-growth // category as above. Still queued to split. - ["src-tauri/src/archive/mod.rs", 1670], + // merge_save_subscription_kinds command + owner_p-kinds TOCTOU fix adds ~30 + // lines. Atomic merge to close the concurrent-seed race. Still queued to split. + ["src-tauri/src/archive/mod.rs", 1695], + // archive/store.rs: merge_owner_p_kinds fn (read+union+upsert under a single + // SQLite tx) + 4 unit tests (create-when-none, adds-kind, idempotent, + // concurrent-interleave). Load-bearing TOCTOU fix for the owner_p shared row. + // Queued to split test module into store_tests.rs in a follow-up. + ["src-tauri/src/archive/store.rs", 1110], ["src-tauri/src/commands/agents.rs", 1437], // #1418 read-path fix: get_thread_replies' blocker fix (shared TIMELINE_KINDS // const + build_thread_replies_filter helper, mirroring the channel sibling so diff --git a/desktop/src-tauri/src/archive/mod.rs b/desktop/src-tauri/src/archive/mod.rs index b2857b018..4d8ae46c3 100644 --- a/desktop/src-tauri/src/archive/mod.rs +++ b/desktop/src-tauri/src/archive/mod.rs @@ -384,6 +384,35 @@ async fn probe_event_readable(state: &AppState, event_id: &str) -> Result<(), St Ok(()) } +// ── merge_save_subscription_kinds ──────────────────────────────────────────── + +/// Atomically merge `kind` into the `owner_p` save subscription for the +/// current identity + relay. +/// +/// Reads the existing `kinds` array, unions in `kind`, and writes back — all +/// inside a single SQLite transaction. This prevents the TOCTOU race where two +/// concurrent seed hooks (observer seed + metric seed) each read an empty row +/// and the last writer clobbers the first. +/// +/// Called by both `useObserverArchiveSeed` (kind 24200) and +/// `useAgentMetricArchiveSeed` (kind 44200) instead of the former +/// list → merge-in-TS → create pattern. +#[tauri::command] +pub fn merge_save_subscription_kinds( + state: State<'_, AppState>, + kind: u32, +) -> Result<(), String> { + if kind > u32::from(u16::MAX) { + return Err(format!("kind {kind} is out of the valid range 0..=65535")); + } + + let identity_pk = identity_pubkey(&state)?; + let relay_url = relay_ws_url_with_override(&state); + let now = now_secs(); + let conn = open_db()?; + store::merge_owner_p_kinds(&conn, &identity_pk, &relay_url, &identity_pk, kind, now) +} + // ── list_save_subscriptions ────────────────────────────────────────────────── /// List all save subscriptions for the current identity + relay. diff --git a/desktop/src-tauri/src/archive/store.rs b/desktop/src-tauri/src/archive/store.rs index b70a96749..7d3956e92 100644 --- a/desktop/src-tauri/src/archive/store.rs +++ b/desktop/src-tauri/src/archive/store.rs @@ -195,6 +195,70 @@ pub fn has_save_subscription( Ok(count > 0) } +/// Atomically merge `new_kind` into the `owner_p` save subscription for the +/// given identity + relay + scope_value. +/// +/// Reads the current `kinds` array, unions in `new_kind`, and writes back — +/// all inside a single SQLite transaction, so concurrent callers can never +/// clobber each other's kind regardless of await interleaving. +/// +/// If no row exists yet it is created with `[new_kind]`. `now` is used as +/// `created_at` only on insert (the conflict clause never updates it). +pub fn merge_owner_p_kinds( + conn: &Connection, + identity_pubkey: &str, + relay_url: &str, + scope_value: &str, + new_kind: u32, + now: i64, +) -> Result<(), String> { + // `unchecked_transaction` matches the rusqlite idiom for a plain + // BEGIN/COMMIT without a savepoint, giving us an exclusive write lock for + // the duration of the read-modify-write. + let tx = conn + .unchecked_transaction() + .map_err(|e| format!("merge_owner_p_kinds begin tx: {e}"))?; + + // Read the current kinds, if any. + let existing_json: Option = tx + .query_row( + "SELECT kinds FROM save_subscriptions + WHERE identity_pubkey = ?1 + AND relay_url = ?2 + AND scope_type = 'owner_p' + AND scope_value = ?3", + params![identity_pubkey, relay_url, scope_value], + |row| row.get::<_, String>(0), + ) + .optional() + .map_err(|e| format!("merge_owner_p_kinds read: {e}"))?; + + // Parse, union, re-serialize. + let mut kinds: Vec = match existing_json { + Some(ref json) => serde_json::from_str(json).unwrap_or_default(), + None => vec![], + }; + if !kinds.contains(&new_kind) { + kinds.push(new_kind); + } + let kinds_json = + serde_json::to_string(&kinds).map_err(|e| format!("merge_owner_p_kinds serialize: {e}"))?; + + // Upsert — INSERT on first call, UPDATE kinds on subsequent. + tx.execute( + "INSERT INTO save_subscriptions + (identity_pubkey, relay_url, scope_type, scope_value, kinds, created_at) + VALUES (?1, ?2, 'owner_p', ?3, ?4, ?5) + ON CONFLICT (identity_pubkey, relay_url, scope_type, scope_value) + DO UPDATE SET kinds = excluded.kinds", + params![identity_pubkey, relay_url, scope_value, kinds_json, now], + ) + .map_err(|e| format!("merge_owner_p_kinds upsert: {e}"))?; + + tx.commit() + .map_err(|e| format!("merge_owner_p_kinds commit: {e}")) +} + /// Return the `kinds` JSON string for a matching save subscription, or `None` /// if no subscription exists. pub fn get_subscription_kinds( @@ -524,6 +588,76 @@ mod tests { assert!(!has_save_subscription(&conn, "pk", "wss://r", "owner_p", "other").unwrap()); } + // ── merge_owner_p_kinds ────────────────────────────────────────────────── + + #[test] + fn test_merge_owner_p_kinds_creates_row_when_none_exists() { + let conn = in_memory(); + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 24200, 1).unwrap(); + let subs = list_save_subscriptions(&conn, "pk", "wss://r").unwrap(); + assert_eq!(subs.len(), 1); + let kinds: Vec = serde_json::from_str(&subs[0].kinds).unwrap(); + assert_eq!(kinds, [24200]); + } + + #[test] + fn test_merge_owner_p_kinds_adds_new_kind_to_existing_row() { + let conn = in_memory(); + // Seed with 24200 first. + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 24200, 1).unwrap(); + // Now merge 44200 in — must produce [24200, 44200]. + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 44200, 2).unwrap(); + let subs = list_save_subscriptions(&conn, "pk", "wss://r").unwrap(); + assert_eq!(subs.len(), 1); + let kinds: Vec = serde_json::from_str(&subs[0].kinds).unwrap(); + assert!(kinds.contains(&24200), "must still contain 24200"); + assert!(kinds.contains(&44200), "must now contain 44200"); + assert_eq!(kinds.len(), 2, "no duplicates"); + } + + #[test] + fn test_merge_owner_p_kinds_idempotent_on_existing_kind() { + let conn = in_memory(); + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 44200, 1).unwrap(); + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 44200, 2).unwrap(); + let subs = list_save_subscriptions(&conn, "pk", "wss://r").unwrap(); + let kinds: Vec = serde_json::from_str(&subs[0].kinds).unwrap(); + assert_eq!(kinds, [44200], "no duplicates after idempotent call"); + } + + /// Simulates the concurrent-interleave race: both seeds read an empty row + /// "simultaneously" (both see None), then each writes its own kind via the + /// atomic merge fn. The last writer must still produce a row with BOTH + /// kinds because the merge fn reads-inside-the-tx, not reads-before-the-tx. + /// + /// In a real concurrent scenario the SQLite write-lock serializes the two + /// transactions. Here we simulate "observer wrote first" by calling + /// merge_owner_p_kinds(24200) then merge_owner_p_kinds(44200) — the second + /// call reads the row that the first call created (within its transaction) + /// and merges 44200 in. The result must be [24200, 44200], not [44200]. + #[test] + fn test_merge_owner_p_kinds_concurrent_interleave_both_kinds_survive() { + let conn = in_memory(); + // Simulate: both seeds start with an empty row (conn starts clean). + // In the real race both would read [] concurrently; with the atomic tx + // one wins the write lock first. Simulate that ordering here. + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 24200, 1).unwrap(); // observer wins lock first + merge_owner_p_kinds(&conn, "pk", "wss://r", "mypk", 44200, 2).unwrap(); // metric runs second + + let subs = list_save_subscriptions(&conn, "pk", "wss://r").unwrap(); + assert_eq!(subs.len(), 1, "exactly one owner_p row"); + let kinds: Vec = serde_json::from_str(&subs[0].kinds).unwrap(); + assert!( + kinds.contains(&24200), + "observer kind 24200 must survive concurrent metric seed" + ); + assert!( + kinds.contains(&44200), + "metric kind 44200 must be present after concurrent seed" + ); + assert_eq!(kinds.len(), 2, "exactly two kinds, no duplicates"); + } + // ── Archived events ────────────────────────────────────────────────────── #[test] diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index bbc759367..8fdafebbc 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -618,6 +618,7 @@ pub fn run() { agent_metric_archive_default_enabled, archive::archive_events, archive::create_save_subscription, + archive::merge_save_subscription_kinds, archive::list_save_subscriptions, archive::delete_save_subscription, archive::read_archived_events, diff --git a/desktop/src/features/local-archive/useAgentMetricArchiveSeed.test.mjs b/desktop/src/features/local-archive/useAgentMetricArchiveSeed.test.mjs index 796c7221c..6a832b4bd 100644 --- a/desktop/src/features/local-archive/useAgentMetricArchiveSeed.test.mjs +++ b/desktop/src/features/local-archive/useAgentMetricArchiveSeed.test.mjs @@ -13,21 +13,16 @@ import test from "node:test"; function makeDeps({ defaultOn = false, hasExplicitChoice = false, - createShouldFail = false, - existingKinds = [], + mergeShouldFail = false, } = {}) { - const calls = { createSaveSubscription: [], setExplicitChoice: [] }; + const calls = { mergeSaveSubscriptionKinds: [], setExplicitChoice: [] }; return { calls, agentMetricArchiveDefaultEnabled: async () => defaultOn, - listSaveSubscriptions: async () => - existingKinds.length > 0 - ? [{ scopeType: "owner_p", kinds: existingKinds }] - : [], - createSaveSubscription: async (scopeType, scopeValue, kinds) => { - if (createShouldFail) throw new Error("create failed"); - calls.createSaveSubscription.push({ scopeType, scopeValue, kinds }); + mergeSaveSubscriptionKinds: async (kind) => { + if (mergeShouldFail) throw new Error("merge failed"); + calls.mergeSaveSubscriptionKinds.push({ kind }); }, hasExplicitChoice: (_pubkey) => hasExplicitChoice, setExplicitChoice: (pubkey, enabled) => { @@ -54,18 +49,7 @@ async function runSeed(pubkey, deps) { if (!defaultOn) return; try { - let existingKinds = []; - try { - const existing = await deps.listSaveSubscriptions(); - existingKinds = - existing.find((s) => s.scopeType === "owner_p")?.kinds ?? []; - } catch { - // best-effort - } - const mergedKinds = existingKinds.includes(KIND_AGENT_TURN_METRIC) - ? existingKinds - : [...existingKinds, KIND_AGENT_TURN_METRIC]; - await deps.createSaveSubscription("owner_p", pubkey, mergedKinds); + await deps.mergeSaveSubscriptionKinds(KIND_AGENT_TURN_METRIC); } catch { return; // transient failure — do NOT set explicit choice } @@ -80,42 +64,12 @@ test("test_internal_build_unset_seeds_owner_p_subscription", async () => { await runSeed("pubkey123", deps); assert.equal( - deps.calls.createSaveSubscription.length, + deps.calls.mergeSaveSubscriptionKinds.length, 1, - "should call createSaveSubscription once", + "should call mergeSaveSubscriptionKinds once", ); - const call = deps.calls.createSaveSubscription[0]; - assert.equal(call.scopeType, "owner_p"); - assert.equal(call.scopeValue, "pubkey123"); - assert.deepEqual(call.kinds, [44200]); -}); - -test("test_internal_build_merges_with_existing_observer_kinds", async () => { - // Observer already seeded [24200]; metric seed must produce [24200, 44200]. - const deps = makeDeps({ - defaultOn: true, - hasExplicitChoice: false, - existingKinds: [24200], - }); - await runSeed("pubkey123", deps); - - assert.equal(deps.calls.createSaveSubscription.length, 1); - const call = deps.calls.createSaveSubscription[0]; - assert.deepEqual(call.kinds, [24200, 44200]); -}); - -test("test_internal_build_idempotent_when_kind_already_present", async () => { - // 44200 already in the row — merged kinds should be the same. - const deps = makeDeps({ - defaultOn: true, - hasExplicitChoice: false, - existingKinds: [24200, 44200], - }); - await runSeed("pubkey123", deps); - - assert.equal(deps.calls.createSaveSubscription.length, 1); - const call = deps.calls.createSaveSubscription[0]; - assert.deepEqual(call.kinds, [24200, 44200]); + const call = deps.calls.mergeSaveSubscriptionKinds[0]; + assert.equal(call.kind, 44200); }); test("test_internal_build_unset_persists_explicit_choice_after_seed", async () => { @@ -136,9 +90,9 @@ test("test_explicit_choice_set_does_not_reseed", async () => { await runSeed("pubkey123", deps); assert.equal( - deps.calls.createSaveSubscription.length, + deps.calls.mergeSaveSubscriptionKinds.length, 0, - "should not call createSaveSubscription when explicit choice is already set", + "should not call mergeSaveSubscriptionKinds when explicit choice is already set", ); assert.equal( deps.calls.setExplicitChoice.length, @@ -152,9 +106,9 @@ test("test_oss_build_does_not_seed", async () => { await runSeed("pubkey123", deps); assert.equal( - deps.calls.createSaveSubscription.length, + deps.calls.mergeSaveSubscriptionKinds.length, 0, - "should not call createSaveSubscription in OSS build", + "should not call mergeSaveSubscriptionKinds in OSS build", ); assert.equal( deps.calls.setExplicitChoice.length, @@ -163,18 +117,18 @@ test("test_oss_build_does_not_seed", async () => { ); }); -test("test_create_failure_does_not_persist_explicit_choice", async () => { +test("test_merge_failure_does_not_persist_explicit_choice", async () => { const deps = makeDeps({ defaultOn: true, hasExplicitChoice: false, - createShouldFail: true, + mergeShouldFail: true, }); await runSeed("pubkey123", deps); assert.equal( deps.calls.setExplicitChoice.length, 0, - "should NOT persist explicit choice after a transient create failure", + "should NOT persist explicit choice after a transient merge failure", ); }); @@ -182,7 +136,7 @@ test("test_empty_pubkey_does_nothing", async () => { const deps = makeDeps({ defaultOn: true, hasExplicitChoice: false }); await runSeed("", deps); - assert.equal(deps.calls.createSaveSubscription.length, 0); + assert.equal(deps.calls.mergeSaveSubscriptionKinds.length, 0); assert.equal(deps.calls.setExplicitChoice.length, 0); }); @@ -190,6 +144,79 @@ test("test_undefined_pubkey_does_nothing", async () => { const deps = makeDeps({ defaultOn: true, hasExplicitChoice: false }); await runSeed(undefined, deps); - assert.equal(deps.calls.createSaveSubscription.length, 0); + assert.equal(deps.calls.mergeSaveSubscriptionKinds.length, 0); assert.equal(deps.calls.setExplicitChoice.length, 0); }); + +// ── Concurrent-interleave test ─────────────────────────────────────────────── +// +// Verifies the scenario Paul identified: on an internal-build first run with +// both flags on and no prior owner_p row, the observer and metric seeds race. +// With the old TS-side list+merge+create pattern the interleave could be: +// +// 1. observer seed: await list() → [] +// 2. metric seed: await list() → [] (row not yet written) +// 3. observer writes [24200] +// 4. metric writes [44200] → clobbers 24200 +// +// The new pattern delegates the merge to Rust under a single SQLite tx. +// Here we model that by tracking a shared "db state" and verifying that +// running both seeds concurrently (Promise.all) leaves both kinds present. + +test("test_concurrent_seeds_both_kinds_survive", async () => { + // Shared in-memory "db" — the atomic merge impl would serialize via SQLite + // write lock; here we simulate by letting calls accumulate and checking + // the final state. + const db = new Set(); // kinds present after all merges + + function makeConcurrentDeps(defaultOn = true) { + return { + agentMetricArchiveDefaultEnabled: async () => defaultOn, + // Simulates the atomic merge: each call simply adds its kind to the set, + // regardless of what was there before (atomicity guarantee). + mergeSaveSubscriptionKinds: async (kind) => { + db.add(kind); + }, + hasExplicitChoice: (_pubkey) => false, + setExplicitChoice: () => {}, + }; + } + + const observerDeps = makeConcurrentDeps(); + const metricDeps = makeConcurrentDeps(); + + // Replace the kind constant in the observer runSeed equivalent with 24200. + async function runObserverSeed(pubkey, deps) { + if (!pubkey) return; + if (deps.hasExplicitChoice(pubkey)) return; + let defaultOn; + try { + defaultOn = await deps.agentMetricArchiveDefaultEnabled(); + } catch { + return; + } + if (!defaultOn) return; + try { + await deps.mergeSaveSubscriptionKinds(24200); + } catch { + return; + } + deps.setExplicitChoice(pubkey, true); + } + + // Run both seeds concurrently — no await between them. + await Promise.all([ + runObserverSeed("pubkey123", observerDeps), + runSeed("pubkey123", metricDeps), + ]); + + assert.ok( + db.has(24200), + "observer kind 24200 must be present after concurrent seeds", + ); + assert.ok( + db.has(44200), + "metric kind 44200 must be present after concurrent seeds", + ); + assert.equal(db.size, 2, "exactly two kinds, no extras"); +}); diff --git a/desktop/src/features/local-archive/useAgentMetricArchiveSeed.ts b/desktop/src/features/local-archive/useAgentMetricArchiveSeed.ts index 0ae1c48d3..520d0e660 100644 --- a/desktop/src/features/local-archive/useAgentMetricArchiveSeed.ts +++ b/desktop/src/features/local-archive/useAgentMetricArchiveSeed.ts @@ -6,9 +6,9 @@ * auto-creates an `owner_p` save subscription including kind 44200 agent turn * metrics, scoped to the current identity's pubkey. * - * Merges with any existing `owner_p` subscription (e.g. an observer - * subscription already seeded) rather than overwriting, so both kinds coexist - * in one row. + * Uses `mergeSaveSubscriptionKinds` (atomic DB-side merge) so a concurrently + * running observer seed (24200) cannot clobber this kind — the union happens + * under a single SQLite transaction regardless of await ordering. * * OSS builds return `false` from `agent_metric_archive_default_enabled` → * no-op. After any explicit user action (seeding or opt-out), the localStorage @@ -19,8 +19,7 @@ import * as React from "react"; import { KIND_AGENT_TURN_METRIC } from "@/shared/constants/kinds"; import { - createSaveSubscription, - listSaveSubscriptions, + mergeSaveSubscriptionKinds, agentMetricArchiveDefaultEnabled, } from "@/shared/api/tauriArchive"; import { @@ -33,22 +32,14 @@ import { */ export interface AgentMetricArchiveSeedDeps { agentMetricArchiveDefaultEnabled: () => Promise; - listSaveSubscriptions: () => Promise< - Array<{ scopeType: string; kinds: number[] }> - >; - createSaveSubscription: ( - scopeType: "owner_p", - scopeValue: string, - kinds: number[], - ) => Promise; + mergeSaveSubscriptionKinds: (kind: number) => Promise; hasExplicitChoice: (pubkey: string) => boolean; setExplicitChoice: (pubkey: string, enabled: boolean) => void; } const defaultDeps: AgentMetricArchiveSeedDeps = { agentMetricArchiveDefaultEnabled, - listSaveSubscriptions, - createSaveSubscription, + mergeSaveSubscriptionKinds, hasExplicitChoice: hasExplicitAgentMetricArchiveChoice, setExplicitChoice: setExplicitAgentMetricArchiveChoice, }; @@ -94,25 +85,12 @@ export function useAgentMetricArchiveSeed( return; } - // Internal build + no prior choice → auto-seed. + // Internal build + no prior choice → auto-seed via atomic DB merge. try { - // Merge with any existing owner_p subscription so a concurrently-seeded - // observer subscription (24200) is not overwritten. - let existingKinds: number[] = []; - try { - const existing = await deps.listSaveSubscriptions(); - existingKinds = - existing.find((s) => s.scopeType === "owner_p")?.kinds ?? []; - } catch { - // Best-effort — on error, seed with just our kind. - } - const mergedKinds = existingKinds.includes(KIND_AGENT_TURN_METRIC) - ? existingKinds - : [...existingKinds, KIND_AGENT_TURN_METRIC]; - await deps.createSaveSubscription("owner_p", pubkey, mergedKinds); + await deps.mergeSaveSubscriptionKinds(KIND_AGENT_TURN_METRIC); } catch (err) { console.warn( - "[useAgentMetricArchiveSeed] createSaveSubscription failed:", + "[useAgentMetricArchiveSeed] mergeSaveSubscriptionKinds failed:", err, ); // Do NOT set the localStorage flag — a transient failure (relay diff --git a/desktop/src/features/local-archive/useObserverArchiveSeed.test.mjs b/desktop/src/features/local-archive/useObserverArchiveSeed.test.mjs index 506f91c6a..54128282d 100644 --- a/desktop/src/features/local-archive/useObserverArchiveSeed.test.mjs +++ b/desktop/src/features/local-archive/useObserverArchiveSeed.test.mjs @@ -19,16 +19,16 @@ import test from "node:test"; function makeDeps({ defaultOn = false, hasExplicitChoice = false, - createShouldFail = false, + mergeShouldFail = false, } = {}) { - const calls = { createSaveSubscription: [], setExplicitChoice: [] }; + const calls = { mergeSaveSubscriptionKinds: [], setExplicitChoice: [] }; return { calls, observerArchiveDefaultEnabled: async () => defaultOn, - createSaveSubscription: async (scopeType, scopeValue, kinds) => { - if (createShouldFail) throw new Error("create failed"); - calls.createSaveSubscription.push({ scopeType, scopeValue, kinds }); + mergeSaveSubscriptionKinds: async (kind) => { + if (mergeShouldFail) throw new Error("merge failed"); + calls.mergeSaveSubscriptionKinds.push({ kind }); }, hasExplicitChoice: (_pubkey) => hasExplicitChoice, setExplicitChoice: (pubkey, enabled) => { @@ -40,6 +40,8 @@ function makeDeps({ // Minimal re-implementation of the seeding logic from useObserverArchiveSeed.ts. // Kept in sync with the source by structural mirroring (not bytewise copy) — // change the source and update this accordingly. +const KIND_AGENT_OBSERVER_FRAME = 24200; + async function runSeed(pubkey, deps) { if (!pubkey) return; if (deps.hasExplicitChoice(pubkey)) return; @@ -54,7 +56,7 @@ async function runSeed(pubkey, deps) { if (!defaultOn) return; try { - await deps.createSaveSubscription("owner_p", pubkey, [24200]); + await deps.mergeSaveSubscriptionKinds(KIND_AGENT_OBSERVER_FRAME); } catch { return; // transient failure — do NOT set explicit choice } @@ -69,14 +71,12 @@ test("test_internal_build_unset_seeds_owner_p_subscription", async () => { await runSeed("pubkey123", deps); assert.equal( - deps.calls.createSaveSubscription.length, + deps.calls.mergeSaveSubscriptionKinds.length, 1, - "should call createSaveSubscription once", + "should call mergeSaveSubscriptionKinds once", ); - const call = deps.calls.createSaveSubscription[0]; - assert.equal(call.scopeType, "owner_p"); - assert.equal(call.scopeValue, "pubkey123"); - assert.deepEqual(call.kinds, [24200]); + const call = deps.calls.mergeSaveSubscriptionKinds[0]; + assert.equal(call.kind, 24200); }); test("test_internal_build_unset_persists_explicit_choice_after_seed", async () => { @@ -97,9 +97,9 @@ test("test_explicit_choice_set_does_not_reseed", async () => { await runSeed("pubkey123", deps); assert.equal( - deps.calls.createSaveSubscription.length, + deps.calls.mergeSaveSubscriptionKinds.length, 0, - "should not call createSaveSubscription when explicit choice is already set", + "should not call mergeSaveSubscriptionKinds when explicit choice is already set", ); assert.equal( deps.calls.setExplicitChoice.length, @@ -113,9 +113,9 @@ test("test_oss_build_does_not_seed", async () => { await runSeed("pubkey123", deps); assert.equal( - deps.calls.createSaveSubscription.length, + deps.calls.mergeSaveSubscriptionKinds.length, 0, - "should not call createSaveSubscription in OSS build", + "should not call mergeSaveSubscriptionKinds in OSS build", ); assert.equal( deps.calls.setExplicitChoice.length, @@ -124,23 +124,18 @@ test("test_oss_build_does_not_seed", async () => { ); }); -test("test_create_failure_does_not_persist_explicit_choice", async () => { +test("test_merge_failure_does_not_persist_explicit_choice", async () => { const deps = makeDeps({ defaultOn: true, hasExplicitChoice: false, - createShouldFail: true, + mergeShouldFail: true, }); await runSeed("pubkey123", deps); - assert.equal( - deps.calls.createSaveSubscription.length, - 0, - "createSaveSubscription should throw (called internally but errors)", - ); assert.equal( deps.calls.setExplicitChoice.length, 0, - "should NOT persist explicit choice after a transient create failure", + "should NOT persist explicit choice after a transient merge failure", ); }); @@ -148,7 +143,7 @@ test("test_empty_pubkey_does_nothing", async () => { const deps = makeDeps({ defaultOn: true, hasExplicitChoice: false }); await runSeed("", deps); - assert.equal(deps.calls.createSaveSubscription.length, 0); + assert.equal(deps.calls.mergeSaveSubscriptionKinds.length, 0); assert.equal(deps.calls.setExplicitChoice.length, 0); }); @@ -156,6 +151,6 @@ test("test_undefined_pubkey_does_nothing", async () => { const deps = makeDeps({ defaultOn: true, hasExplicitChoice: false }); await runSeed(undefined, deps); - assert.equal(deps.calls.createSaveSubscription.length, 0); + assert.equal(deps.calls.mergeSaveSubscriptionKinds.length, 0); assert.equal(deps.calls.setExplicitChoice.length, 0); }); diff --git a/desktop/src/features/local-archive/useObserverArchiveSeed.ts b/desktop/src/features/local-archive/useObserverArchiveSeed.ts index fb1662742..f547493da 100644 --- a/desktop/src/features/local-archive/useObserverArchiveSeed.ts +++ b/desktop/src/features/local-archive/useObserverArchiveSeed.ts @@ -2,12 +2,13 @@ * First-run seeding for observer-feed archive. * * When an internal build has `BUZZ_BUILD_OBSERVER_ARCHIVE_DEFAULT` set and the - * current identity has not yet made an explicit choice, this hook auto-creates - * an `owner_p` save subscription including kind 24200 observer frames, scoped - * to the current identity's pubkey. + * current identity has not yet made an explicit choice, this hook + * auto-creates an `owner_p` save subscription including kind 24200 observer + * frames, scoped to the current identity's pubkey. * - * Merges with any existing `owner_p` subscription (e.g. a metric subscription - * already seeded) rather than overwriting, so both kinds coexist in one row. + * Uses `mergeSaveSubscriptionKinds` (atomic DB-side merge) so a concurrently + * running metric seed (44200) cannot clobber this kind — the union happens + * under a single SQLite transaction regardless of await ordering. * * OSS builds return `false` from `observer_archive_default_enabled` → no-op. * After any explicit user action (seeding or opt-out), the localStorage flag @@ -18,8 +19,7 @@ import * as React from "react"; import { KIND_AGENT_OBSERVER_FRAME } from "@/shared/constants/kinds"; import { - createSaveSubscription, - listSaveSubscriptions, + mergeSaveSubscriptionKinds, observerArchiveDefaultEnabled, } from "@/shared/api/tauriArchive"; import { @@ -32,22 +32,14 @@ import { */ export interface ObserverArchiveSeedDeps { observerArchiveDefaultEnabled: () => Promise; - listSaveSubscriptions: () => Promise< - Array<{ scopeType: string; kinds: number[] }> - >; - createSaveSubscription: ( - scopeType: "owner_p", - scopeValue: string, - kinds: number[], - ) => Promise; + mergeSaveSubscriptionKinds: (kind: number) => Promise; hasExplicitChoice: (pubkey: string) => boolean; setExplicitChoice: (pubkey: string, enabled: boolean) => void; } const defaultDeps: ObserverArchiveSeedDeps = { observerArchiveDefaultEnabled, - listSaveSubscriptions, - createSaveSubscription, + mergeSaveSubscriptionKinds, hasExplicitChoice: hasExplicitObserverArchiveChoice, setExplicitChoice: setExplicitObserverArchiveChoice, }; @@ -93,25 +85,12 @@ export function useObserverArchiveSeed( return; } - // Internal build + no prior choice → auto-seed. + // Internal build + no prior choice → auto-seed via atomic DB merge. try { - // Merge with any existing owner_p subscription so a concurrently-seeded - // metric subscription (44200) is not overwritten. - let existingKinds: number[] = []; - try { - const existing = await deps.listSaveSubscriptions(); - existingKinds = - existing.find((s) => s.scopeType === "owner_p")?.kinds ?? []; - } catch { - // Best-effort — on error, seed with just our kind. - } - const mergedKinds = existingKinds.includes(KIND_AGENT_OBSERVER_FRAME) - ? existingKinds - : [...existingKinds, KIND_AGENT_OBSERVER_FRAME]; - await deps.createSaveSubscription("owner_p", pubkey, mergedKinds); + await deps.mergeSaveSubscriptionKinds(KIND_AGENT_OBSERVER_FRAME); } catch (err) { console.warn( - "[useObserverArchiveSeed] createSaveSubscription failed:", + "[useObserverArchiveSeed] mergeSaveSubscriptionKinds failed:", err, ); // Do NOT set the localStorage flag — a transient failure (relay diff --git a/desktop/src/shared/api/tauriArchive.ts b/desktop/src/shared/api/tauriArchive.ts index 83f5a1311..e701ea1cf 100644 --- a/desktop/src/shared/api/tauriArchive.ts +++ b/desktop/src/shared/api/tauriArchive.ts @@ -110,6 +110,22 @@ export async function agentMetricArchiveDefaultEnabled(): Promise { return invokeTauri("agent_metric_archive_default_enabled"); } +/** + * Atomically merge `kind` into the `owner_p` save subscription for the + * current identity + relay. + * + * Performs a read-modify-write inside a single SQLite transaction on the Rust + * side, so concurrent callers (e.g. observer seed + metric seed racing on + * first run) cannot clobber each other's kind. + * + * Called by both `useObserverArchiveSeed` and `useAgentMetricArchiveSeed` + * instead of the former list → merge-in-TS → create pattern. + */ +export async function mergeSaveSubscriptionKinds(kind: number): Promise { + await invokeTauri("merge_save_subscription_kinds", { kind }); + notifySubscriptionChange(); +} + /** * Create a save subscription. * Runs an access probe on the backend (channel membership, event readability).